0
\$\begingroup\$

I am learning C and this is an exercise from The C Programmnig Languange by Brian and Ritchie.

Write a program "detab" that replaces tabs in the input with the proper number of blanks to space to the next tab stop. Assume a fixed set of tab stops, say every \$n\$ columns. Should \$n\$ be a variable or a symbolic parameter?

Here's my try, and I've made \$n\$ a parameter. I would appreciate any feedback and explanation on symbolic parameter.

#include <stdio.h>

#define TABLENGTH 8

void detab(int n);

int main () {

  int c, noOfTabs;
  noOfTabs = 0;

  while ((c = getchar()) != EOF) {

    if (c == '\t') {
      ++noOfTabs;
    } else if (noOfTabs > 0) {
      detab(noOfTabs);
      noOfTabs = 0;
      putchar(c);
    }

  }

  return 0;
}


void detab (int n) {

  while (n > 0) {
    --n;
    int i;
    for (i = 0; i < TABLENGTH; ++i) {
      putchar(' ');
    }
  }

}
\$\endgroup\$
3
\$\begingroup\$

The code is not ready for review, because it does not solve the exercise. It blindly replaces each tab with TABLENGTH spaces. This is not detabbing; the amount of blanks must give you a next tab stop. For example, for

a\tb
aa\tb
aaa\tb

the output should be

a       b
aa      b
aaa     b

(number of blanks is 7, 6, and 5 respectively, to align b at the tab stop, the 8th column). Your code produces

a        b
aa        b
aaa        b

instead.

\$\endgroup\$
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.