I have a program that defines a variable int data
The program uses scanf("%d",&data)
to read data from stdin.
If the data from stdin is not an integer, I have to print error message.
I tried if(scanf("%d",&data) ==EOF){ printf("error");return 1;}
It didn`t works for me. So, how can I determine if scanf failed or succeeded?
scanf
's return value is an integer, telling you how many items were succesfully read. If your single integer was read successfully, scanf
will return 1.
e.g.
int items_read = scanf("%d", &data);
if (items_read != 1) {
//It was not a proper integer
}
There is a great discussion on reading integers here, on Stack Overflow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With