muahahahh
muahahahh

Reputation: 69

printf symbols with multiple space characters?

I have the following code to replace tab occurrences in stdin to four spaces.
When I have stdin, separated by two spaces, e.g. "tab tab", the final printf prints the correct string "tab tab", however when my input is tab separated "tab tab", and then four space characters are added instead, the final printf prints only "tab" string and nothing more. Any advice appreciated.

#include <stdio.h>
#define MAX 1000
#define TAB 4

void read_stdin(char s[], int len);

int main(){
    char str[MAX];
    read_stdin(str, MAX);
    return 0;
};

void read_stdin(char s[], int len){
    int i, ii;
    int c;
    for (i = 0; i < len && (c = getchar()) != EOF; i++){
        printf("c = %d, i = %d\n", c, i);

        if (c == '\t'){
            for (ii = 0; ii < TAB; ii++){
                printf("space ");
                s[i] = ' ';
                i++;
                printf("i = %d\n", i);
            };
        } else {
            s[i] = c;
        };
    };

    s[i] = '\0';
    printf("last i = %d\n", i);
    printf("string completed: %s\n", s);
};

in console, tabs separated by space character

tab tab
c = 116, i = 0
c = 97, i = 1
c = 98, i = 2
c = 32, i = 3
c = 116, i = 4
c = 97, i = 5
c = 98, i = 6
c = 10, i = 7
last i = 8
string completed: tab tab

and tabs separated by tab character

tab tab
c = 116, i = 0
c = 97, i = 1
c = 98, i = 2
c = 9, i = 3
space i = 4
space i = 5
space i = 6
space i = 7
c = 116, i = 8
c = 97, i = 9
c = 98, i = 10
c = 10, i = 11
last i = 12
string completed: tab

Upvotes: 1

Views: 504

Answers (1)

dbush
dbush

Reputation: 223872

You're incrementing i one time too many in the inner loop.

After the inner loop exits, i has the value 7 which would be the index of the next character to input. But then the outer loop iterates, increasing i once more. So you skip writing to index 7. When you later try to print s, it reads this uninitialized character. This character happens to have the value 0 in your particular case so the string appears to end there.

Decrement i at the end of the inner loop to put it back in the correct place.

        for (ii = 0; ii < TAB; ii++){
            printf("space ");
            s[i] = ' ';
            i++;
            printf("i = %d\n", i);
        };
        i--;

Upvotes: 3

Related Questions