Validation check with scanf does not work inside a loop

前端 未结 1 461
自闭症患者
自闭症患者 2021-01-07 13:07

I am trying to make a function to check the input of the user and let them try again in case they enter a wrong kind of input.

So when I enter a wrong input into the

相关标签:
1条回答
  • 2021-01-07 13:33

    allowed to use only getchar and scanf for user input.

    Using fgets() would be better. But to live with that restriction ....


    When scanf(" %d ", &size ); returns 0, the non-numeric input remains in stdin.

    Code needs to consume the invalid input - that is missing from OP's code.

    For consistency, even with good input, consume the rest of the line too. This code does not detect if trailing junk exists after the good input on the same line.

    The 2nd space in " %d " is also a problem. A " " directs scanf() to read all white space until some non white space is detected. This means scanf(" %d ", &size ); will not return until something like "123\n4\n" is entered. The 4 is read, determined not to be a white space and put back for later input. Drop the trailing white-space from the format.

    Code also has a problem should an input return EOF (end-of-file or rare input error). The function sizeOfField() has no way to convey end-of-file. Function could be re-defined or for now, simple exit the program.

    int sizeOfField(void) {
      int inputCheck;
    
      do {
        int size;
        inputCheck = scanf("%d", &size);
        if (inputCheck == EOF) {
          break;
        }
    
        // consume rest of line
        int ch;
        while ((ch = getchar()) != '\n' && ch != EOF);
    
        if (inputCheck == 1) {
          return size;
        }
    
        if (ch == EOF) {
          break;
        }
    
        // Non-numeric input occurred.
        printf("Invalid Input!\n" "Try again");
        fflush(stdout);
      }
    
      // No recovery possible
      exit(EXIT_FAILURE);  
    }
    

    Curiously this is a case where " %d" has benefit over "%d". When input is non-numeric, code is certain at least all leading white space (including '\n') are consumed. The specifications about what charterers are put back due to being non-numeric into stdin are problematic if more that one character needs to be "put back" into stdin. Without that assurance, while ((ch = getchar()) != '\n' && ch != EOF); may not consume all the offending non-numeric input.

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