How to prevent users from inputting letters or numbers?

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

    You should not use scanf to read in numbers - see http://www.gidnetwork.com/b-63.html

    Use fgets instead.

    However, if you must use scanf, you can do this:

      #include <stdio.h>
      int main() {
          char text[20];
          fputs("enter some number: ", stdout);
          fflush(stdout);
          if ( fgets(text, sizeof text, stdin) ) {
              int number;
              if ( sscanf(text, "%d", &number) == 1 ) {
                  printf("number = %d\n", number);
              }
          }
          return 0;
      }
    
    0 讨论(0)
  • 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 <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    ...
    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.

    0 讨论(0)
  • 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)

    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题