简体   繁体   中英

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!
       }
    }

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 ...

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 */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM