1
\$\begingroup\$

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;
}
\$\endgroup\$
3
\$\begingroup\$
  • 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.

\$\endgroup\$
  • \$\begingroup\$ Yes, i noticed that too.But couldnt solve.Do you know how would i solve that ?? \$\endgroup\$ – Muhamed Cicak Sep 30 '16 at 22:08
  • \$\begingroup\$ 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). \$\endgroup\$ – vnp Sep 30 '16 at 22:12
  • \$\begingroup\$ @MuhamedCicak Is this supposed to be K&R Exercise 1-21? It's rather tricky to implement correctly. See examples 1 and 2. \$\endgroup\$ – 200_success Sep 30 '16 at 23:32
  • \$\begingroup\$ @200_success Thanks for the nice examples :) \$\endgroup\$ – Muhamed Cicak Oct 2 '16 at 14:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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