I wrote a program that replaces tabs with spaces. First, I defined a maximum length of an input string in the constant MAX_LIMIT
. Next, I declared the procedure detab
that takes two arguments: an input string and a maximum length. In the procedure I read characters until encountering EOF. I'm replacing tabs with four spaces and I'm checking if index
is equal to limit
, and if yes, then I break the loop. Finally, I created a str
character array. I called on it the detab
procedure and I printed out the value of str
in main
.
main.c
#include <stdio.h>
#define MAX_LIMIT 1000
void detab(char str[], int limit);
int main(void) {
char str[MAX_LIMIT];
detab(str, MAX_LIMIT);
printf("%s", str);
return 0;
}
void detab(char str[], int limit) {
char current;
int index = 0;
int stop = 0;
while ((current = getchar()) != EOF) {
if (stop) {
break;
}
if (current == '\t') {
for (int i = 0; i < 4 && !stop; i++) {
if (index == limit) {
stop = 1;
} else {
str[index++] = ' ';
}
}
} else {
str[index++] = current;
}
}
}
How can I improve this program? Is it an optimal solution of this problem?
-
\$\begingroup\$ Possible duplicate of K&R 1-20 Converting tabs to spaces using idiomatic C \$\endgroup\$user33306– user333062017年06月24日 04:19:10 +00:00Commented Jun 24, 2017 at 4:19
-
\$\begingroup\$ @tinstaafl A question is not a duplicate here if it solves the same problem as code in some other question. And the code seems sufficiently different not to be a direct copy. \$\endgroup\$Graipher– Graipher2017年06月24日 08:58:30 +00:00Commented Jun 24, 2017 at 8:58
1 Answer 1
First of all, it is not exactly doing what is expected of
detab
. The visual appearance of the detabbed text shall remain the same. You need to insert as many spaces as required to reach the next tab stop, not necessarily 4 of them.For example, a string
ab\tc
should becomeab c
(2 spaces inserted) whereas your code produces
ab c
detab
does not zero-terminate the string. It is an (un)lucky coincidence that the code produces meaningful output.The limit condition is only tested during the tab expansion. A long sequence of ordinary characters will overrun the buffer.