I'm currently reading the infamous K&R C book and trying to solve Exercise 1-20. My solution looks kind of too simple, but it works. I've searched the web for different solutions, but they all are much longer, although I didn't see any improvement compared to my code. Do you see anything which might compromise my approach? The exercise is as follows:
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?
And here's my solution:
#include <stdio.h>
#define COLS 8
int main (void)
{
int ch;
int charCounter = 0;
while ((ch = getchar()) != EOF) {
if (ch != '\t'){
putchar(ch);
charCounter++;
}
if (ch == '\t'){
for (int i = 0; i < (COLS - (charCounter % COLS)); ++i) {
putchar(' ');
}
charCounter = 0;
}
if (ch == '\n'){
charCounter = 0;
}
}
}