scanf is the number of normal reads, so just judge the return value.
if(scanf("%d", &a) == 1)
printf("OK!");
else
printf("Failed to read an integer.");
But a big pitfall of scanf is that it will stop scanning when it encounters invalid characters and leave invalid characters in the buffer, so it will always detect failures and enter an infinite loop. If you encounter this problem, you can use the following solutions to solve it:
int a;
while(1 != scanf("%d", &a)) {
fflush(stdin); // 刷新缓冲区
cout << "Invalid input! Please check and input again: ";
}
cout << "a = " << a << endl;
cout << "Test finished!";
return 0;
Of course, this is not a good choice. It is best to avoid using scanf in this situation. You can read the string first, then check the string validity, and use some library functions (such as sscanf, isdigit, atoi, etc.) to convert a string into an integer.
The return value of
scanf
is the number of normal reads, so just judge the return value.But a big pitfall of
scanf
is that it will stop scanning when it encounters invalid characters and leave invalid characters in the buffer, so it will always detect failures and enter an infinite loop. If you encounter this problem, you can use the following solutions to solve it:Of course, this is not a good choice. It is best to avoid using
scanf
in this situation. You can read the string first, then check the string validity, and use some library functions (such assscanf
,isdigit
,atoi
, etc.) to convert a string into an integer.I remember doing similar questions in my freshman year, and they were all judged using regular expressions.