问题
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?
回答1:
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.
回答2:
scanf returns the number of items successfully read. You can check if it failed by checking against 1, because you're reading one item:
if (scanf("%d", &data) != 1)
// error
来源:https://stackoverflow.com/questions/8186115/how-can-i-determine-if-scanf-read-what-was-specified-in-format