khalfella

ansi_c_pg34_ch01_ex21.c

Sep 27th, 2014
296
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. /*
  2. * Exercise 1-21.
  3. * Write a program entab that replaces strings of blanks by the minimum number
  4. * of tabs and blanks to achieve the same spacing. Use the same tab stops as for
  5. * detab. When either a tab or a single blank would suffice to reach a tab stop,
  6. * which should be given preference?
  7. */
  8.  
  9. #include <stdio.h>
  10.  
  11.  
  12. #define TABSTOP 8
  13.  
  14. int
  15. main() {
  16. int c;
  17. int offset = 0;
  18. int spaces = 0;
  19.  
  20. while ((c = getchar()) != EOF) {
  21. if (c == ' ') {
  22. spaces++;
  23. } else {
  24.  
  25. if (spaces) {
  26.  
  27. if (spaces + (offset%TABSTOP) > TABSTOP) {
  28. spaces += (offset%TABSTOP);
  29. }
  30. offset += spaces;
  31.  
  32. while (spaces > TABSTOP) {
  33. putchar('\t');
  34. spaces -= TABSTOP;
  35. }
  36.  
  37. while (spaces) {
  38. spaces--;
  39. putchar(' ');
  40. }
  41. }
  42.  
  43. if (c == '\n')
  44. offset = 0;
  45. else if (c == '\t')
  46. offset += TABSTOP - (offset%TABSTOP);
  47. else
  48. offset++;
  49.  
  50. putchar(c);
  51. }
  52. }
  53.  
  54. return (0);
  55. }
Advertisement
Add Comment
Please, Sign In to add comment