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;
}
200_success
146k22 gold badges190 silver badges478 bronze badges
asked Sep 30, 2016 at 18:56
\$\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.

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.