Search code examples
getchar

What is the use of getchar() != in this piece of code?


In this little piece of code in don't get what the useof getchar is. They ask the user to enter an int value and I have to check if it´s valid or not. I understand status, it should check if there's only 1 value entered.

thank you in advance.

#include <stdio.h> 
int main(void)
{

    int x;
    int status;
    status = scanf("%i", &x);
    if ((status != 1) || (getchar() != ’\n’)){
    printf("\nUnvalid entry\n");
    return 1;
}
printf("\nValid entry\n");
return 0;
}

Solution

  • The function getchar() in your program ensures that the user enters only one argument. getchar() asks for the next character from the input. So if you entered '1','2',[Space],[ENTER] getchar returns the char ' ', and in our case it means that we have more than one argument.