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?