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\$
1

1 Answer 1

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\$
4
  • \$\begingroup\$ Yes, i noticed that too.But couldnt solve.Do you know how would i solve that ?? \$\endgroup\$
    – Silidrone
    Sep 30, 2016 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, 2016 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\$ Sep 30, 2016 at 23:32
  • \$\begingroup\$ @200_success Thanks for the nice examples :) \$\endgroup\$
    – Silidrone
    Oct 2, 2016 at 14:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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