user2948936
user2948936

Reputation: 11

Requesting int input, how to guard against char?

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

Answers (2)

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

user2031271
user2031271

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

Related Questions