Reputation: 11
I'm asking for int input, and then checking whether it is equal to the correct answer, but how do I guard against users inputting chars?
int main()
{
int response;
int answer;
scanf("%f", &response);
if(response == answer)
{
//Correct!
}
else
{
//Incorrect!
}
}
Upvotes: 1
Views: 260
Reputation: 1
scanf(3) gives a result (the count of successfully read items), that you should use. And your %f
is incorrect, so you should code
if (scanf(" %d", &response)==1) {
/// did got some response
}
I took into account the good comment of Jonathan Leffler in the answer of Soumya Koumar ...
Upvotes: 3
Reputation:
You will have to use %d
for scanning an int from input.
According to scanf
definition it returns the number of items scanned if successful or 0 in case there is a matching failure. So if you enter a char instead of an integer in the standard input it will return 0 as the return value.
You can do something like:
if (scanf(....) == 0) {
/* error */
} else {
/* do my work */
}
Upvotes: 3