Search code examples
cstringinputscanfgetchar

Why doesnt getchar() stop reading strings in C?


I want the user to be able to input a number n and then the program will read n strings from the user. But now the program wont stop reading strings.

#include <stdio.h>

#define STRING_MAX 10

int main (void)
{
    char string[STRING_MAX];
    int count;
    int total;
    int n, i;
    int chr;

    scanf("%d", &n);

    for(i=0; i<n; i++)
    {
        do {
            count = 0;
            total = 0;
            while ((chr = getchar() != EOF)&& (chr != '\n'))
            {
                if (count < STRING_MAX - 1)
                    string[count++] = chr;
                total += 1;
            }
            string[count] = '\0';
        } while (total > STRING_MAX - 1);
        printf("The input string was:\n\t%s\n", string);
    }
    return 0;
}

Solution

  • Because you have an operator precendence problem here

    chr = getchar() != EOF
    

    this is evaluated as

    chr = (getchar() != EOF)
    

    because the != operator has higher precendence than the assignment operator =, so you just need to add parentheses like this

    (chr = getchar()) != EOF
    

    Tip: Check the return value from scanf() before accessing n, because if the input is invalid you would try to use n while it's uninitialized which would cause undefined behavior.