Daniel Calendini
Daniel Calendini

Reputation: 3

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;
}

Upvotes: 0

Views: 57

Answers (2)

Ido Segal
Ido Segal

Reputation: 422

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.

Upvotes: 1

Vinod Kumar Kashyap
Vinod Kumar Kashyap

Reputation: 103

getchar() basically checks for the character.

getchar() != ’\n’ checks that the character is not a newline character.

you can visit https://www.geeksforgeeks.org/difference-getchar-getch-getc-getche/ to get more out of this

Upvotes: 0

Related Questions