How to stop user entering char as int input in C

前端 未结 5 1555
北恋
北恋 2020-12-20 06:17

Heres a part of my code:

    printf(\"\\nEnter amount of adult tickets:\");
    scanf(\"%d\", &TktAdult);
    while (TktAdult<0){
        printf(\"\\n         


        
相关标签:
5条回答
  • 2020-12-20 06:52

    ... stop user from entering a negative value ...

    is not possible. Users enter all sorts of gibberish. Instead, read a line of user input and parse it for correctness. Use fgets() for input, then sscanf(), strtol(), etc. for parsing.

    // return -1 on EOF
    int GetPositiveNumber(const char *prompt, const char *reprompt) {
      char buf[100];
      fputs(prompt, stdout);
      fflush(stdout);
      while (fgets(buf, sizeof buf, stdin)) [
        int value;
        if (sscanf(buf, "%d", &value) == 1 && value > 0) {
          return value;
        }
        fputs(reprompt, stdout);
        fflush(stdout);
      }
      return -1;
    }
    
    // Usage
    int TktAdult = GetPositiveNumber(
        "\nEnter amount of adult tickets:" , 
        "\nPlease enter a positive number!");
    if (TktAdult < 0) Handle_End_of_File();
    else Success(TktAdult);
    
    0 讨论(0)
  • 2020-12-20 06:54

    but how do I add to it so it also stops user from entering a char??

    You can't prevent user from entering character values. What you can do is check if tktAdult was successfully scanned. If not, flush out everything from stdin:

     bool valid = false;
     while (true) {
     ...
    
        if (scanf("%d", &TktAdult) != 1) {
           int c;
           while ((c = getchar()) != EOF && c != '\n');
        } else {
           break;
        }
    }
    

    The better alternative is to use fgets() and then parse the line using sscanf().

    Also see: Why does everyone say not to use scanf? What should I use instead?.

    0 讨论(0)
  • 2020-12-20 06:54
    #include <stdio.h>
    
    int main() {
        int x = 0.0;
        int readReasult;
        while(1)
        {
            readReasult = scanf("%d",&x);
            if (readReasult < 0) break;
            if (readReasult == 1) {
                if (x >= 0)
                    printf("next number: %d\n", x);
                else
                    printf("negative value not expected\n");
            } else {
                clearerr(stdin);
                scanf("%*s");
                printf("wrong input\n");
            }
        }
    
        return 0;
    }
    

    https://godbolt.org/z/xn86qz

    0 讨论(0)
  • 2020-12-20 06:56

    The following code rejects user input that are:

    • non-numeric as handled by // 1;
    • negative numbers as handled by // 2;
    • positive numbers followed by non-numeric chars as handled by //3

      while (1) {
          printf("\nEnter amount of adult tickets: ");
          if (scanf("%d", &TktAdult) < 0 ||  // 1
                  TktAdult < 0 ||  // 2
                  ((next = getchar()) != EOF && next != '\n')) {  // 3
              clearerr(stdin);
              do
                  next = getchar();
              while (next != EOF && next != '\n');  // 4
              clearerr(stdin);
              printf("\nPlease enter a positive number!");
          } else {
              break;
          }
      }
      

    Also, // 4 clears the standard input of buffered non-numeric characters following case // 3 (i.e. 123sda - scanf takes 123 but leaves 'sda' in the buffer).

    0 讨论(0)
  • 2020-12-20 07:00
    // You can try this,  Filter all except for the digital characters
    int TktAdult;
    char ch;
    char str[10];
    int i = 0;
    printf("\nEnter amount of adult tickets:");
    while ((ch = getchar()) != '\n')
    {
        // Filter all except for the digital characters
        if(!isalpha(ch) && isalnum(ch))
            str[i++] = ch;
    }
    str[i] = '\0';
    TktAdult = atoi(str);
    printf("Done [%d]\n", TktAdult);
    
    0 讨论(0)
提交回复
热议问题