How to stop user entering char as int input in C

前端 未结 5 1587
北恋
北恋 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: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).

提交回复
热议问题