Replace tabs with spaces 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 &lt;stdio.h&gt;
#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 &lt; 4 &amp;&amp; !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?
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 become

ab  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.