# Spaces to tabs converter

I wrote a program to convert spaces to tabs. If there are 4 spaces it should convert them to tab. Please let me know how to improve it.

#include <stdio.h>
#define TABVALUE 4
int c, d, s;

int main(void) {
c = s = d = 0;
while ((c = getchar()) != EOF) {
if (c == ' ') {
s++;
for (int j = 0; j < TABVALUE - 1; j++) {
d = getchar();
if (d == ' ') {
s++;
}
}
if (s == TABVALUE) {
putchar('\t');
s = 0;
}
} else {
putchar(c);
}
}
return 0;
}


• Bugs

j unconditionally loops to TABVALUE - 1. This is wrong:

• If d happens to not be a space, it is not printed out.
• If next d happens to be a space, it is still counted.

Test against a b cdef. The output is a\tf.

• Yes, i noticed that too.But couldnt solve.Do you know how would i solve that ?? Sep 30 '16 at 22:08
• Rewrite the inner loop as while ((c = getchar()) == ' '). Count spaces and break the loop at right time. Print either spaces or a tab. Only then print c. Care about special cases (newline for example).
– vnp
Sep 30 '16 at 22:12
• @MuhamedCicak Is this supposed to be K&R Exercise 1-21? It's rather tricky to implement correctly. See examples 1 and 2. Sep 30 '16 at 23:32
• @200_success Thanks for the nice examples :) Oct 2 '16 at 14:09