Verify validation with scanf does not work inside a loop

I am trying to make a function to check user input and ask them to try again if they enter the wrong input type.

Therefore, when I enter the wrong input into a function, it throws me into an infinite loop. What can I do to fix this?

I may only be used getcharand scanffor user input.

int sizeOfField()
{
    int size,inputCheck,flag=0;

    while (!flag)
    {
        inputCheck= scanf(" %d ", &size );
        if ( inputCheck < 1 )
        {
            printf( "Invalid Input!\n" );
            printf( "Try agian");
        } else if (inputCheck == 1)
        flag=1;
    }
    return size;
}
0
source share
1 answer

only getchar and scanf are allowed for user input.

Use fgets()would be better. But living with this restriction ....


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

- OP-.

, , . , .

" %d " . A " " scanf() , . , scanf(" %d ", &size ); , - "123\n4\n". 4 , . .

, EOF ( ). sizeOfField() . .

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);  
}

, , " %d" "%d". , , , ( '\n') . , - stdin, , , "" stdin. while ((ch = getchar()) != '\n' && ch != EOF); .

+2

Source: https://habr.com/ru/post/1690877/


All Articles