\$\begingroup\$
\$\endgroup\$
1
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
-
\$\begingroup\$ Follow-up question \$\endgroup\$200_success– 200_success2016年10月03日 16:23:38 +00:00Commented Oct 3, 2016 at 16:23
1 Answer 1
\$\begingroup\$
\$\endgroup\$
4
Bugs
j
unconditionally loops toTABVALUE
- 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 isa\tf
.- If
answered Sep 30, 2016 at 21:02
-
\$\begingroup\$ Yes, i noticed that too.But couldnt solve.Do you know how would i solve that ?? \$\endgroup\$Silidrone– Silidrone2016年09月30日 22:08:50 +00:00Commented 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 printc
. Care about special cases (newline for example). \$\endgroup\$vnp– vnp2016年09月30日 22:12:46 +00:00Commented 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\$200_success– 200_success2016年09月30日 23:32:58 +00:00Commented Sep 30, 2016 at 23:32
-
\$\begingroup\$ @200_success Thanks for the nice examples :) \$\endgroup\$Silidrone– Silidrone2016年10月02日 14:09:52 +00:00Commented Oct 2, 2016 at 14:09
lang-c