How to prevent users from inputting letters or numbers?

前端 未结 4 909
闹比i
闹比i 2021-01-06 03:13

I have a simple problem;

Here is the code :

#include
main(){
 int input;
 printf(\"Choose a numeric value\");
 scanf(\"%d\",&input         


        
4条回答
  •  爱一瞬间的悲伤
    2021-01-06 04:13

    You can't prevent the user from entering anything he wants -- you can only ignore anything s/he enters that you don't "like".

    A typical pattern is to read a string with fgets, then scan through the string and check that all the input was digits with isdigit. If it was all digits, then convert to an integer; otherwise, throw it away and get the input again.

    Alternatively, use strtol to do the conversion. It sets a pointer to the end of the data it could convert to a number; in this case you (apparently) want it to point to the end of the string.

    If you don't mind some non-portable code, you can read one character at a time, and throw away anything but digits (e.g. with getch on Windows).

提交回复
热议问题