How to prevent users from inputting letters or numbers?

前端 未结 4 914
闹比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 03:58

    The strtol library function will convert a string representation of a number to its equivalent integer value, and will also set a pointer to the first character that does not match a valid number.

    #include 
    #include 
    #include 
    ...
    int value;
    char buffer[SOME_SIZE];
    char *chk;
    do 
    {
      printf("Enter a number: ");
      fflush(stdout);
      if (fgets(buffer, sizeof buffer, stdin) != NULL)
      {
        value = (int) strtol(buffer, &chk, 10); /* assume decimal format */
      }
    } while (!isspace(*chk) && *chk != 0);
    

    If chk points to something other than whitespace or a string terminator (0), then the string was not a valid integer constant. For floating-point input, use strtod.

提交回复
热议问题