Search code examples
cgetchar

What is the correct way to read a series of characters using getchar?


I have two examples of source code. I have always used the first example, but strangely the character '0' I find it at the beginning of the array (which with the second example does not happen). Why does the first example put the character '0' at the beginning of the array?

example1:

/*
    Enter a sentence: ciao
    0 -> \0
    1 -> c
    2 -> i
    3 -> a
    4 -> o
    5 -> \0
*/

#include <stdio.h>
#define MAX 6

int main(void) {
    int i = 0;
    char ch, last_char, sentence[MAX] = { };

    printf("Enter a sentence: ");

    while ((ch = getchar()) != '\n' && i++ < MAX) {
        sentence[i] = ch;
    }

    for(i = 0; i < MAX; ++i) {
        if(sentence[i] == '\0')
            printf("%d -> \\0\n", i);
        else
            printf("%d -> %c\n", i, sentence[i]);
    }
    return 0;
}

example2:

/*
    Enter a sentence: ciao
    0 -> c
    1 -> i
    2 -> a
    3 -> o
    4 -> \0
    5 -> \0
*/

#include <stdio.h>
#define MAX 6

int main(void) {
    int i = 0;
    char ch, last_char, sentence[MAX] = { };

    printf("Enter a sentence: ");

    while ((ch = getchar()) != '\n') {
        sentence[i] = ch;
        if(i++ >= MAX - 1) break;   
    }

    for(i = 0; i < MAX; ++i) {
        if(sentence[i] == '\0')
            printf("%d -> \\0\n", i);
        else
            printf("%d -> %c\n", i, sentence[i]);
    }
    return 0;
}

Solution

  • It's because you're doing i++ in the while condition. So it's incrementing i before you use it as the index in the assignment. You can test the index without incrementing it, and do the auto-increment in the assignment.

        while ((ch = getchar()) != '\n' && i < MAX) {
            sentence[i++] = ch;
        }
    

    You should actually change the order of the && operands. There's no point in reading a character if you've reached the end of the array and won't be able to assign it.

        while (i < MAX && (ch = getchar()) != '\n') {
            sentence[i++] = ch;
        }