How to prevent users from inputting letters or numbers?

前端 未结 4 930
闹比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:08

    Personally, I would read the input into a buffer and scan that string for my number.

    char buffer[100];
    float value;
    do {
    scanf("%s", buffer);
    } while ( sscanf(buffer,"%f", &value) != 1 )

    This will loop until the first thing the user enters on the line is a number. The input could be anything but will only get past this block when the first thing entered is a number.
    example input:
    43289 (value is 43289)
    43.33 (value is 43.44)
    392gifah (value is 392)
    ajfgds432 (continues to loop)

提交回复
热议问题