How to handle exception when scanf of integer gets a character

后端 未结 4 432
南笙
南笙 2021-01-21 09:08

The following simple program would give an endless loop when the input is a character, though it meant to tell a character from a digit. How to test if scanf gets a

4条回答
  •  长情又很酷
    2021-01-21 09:14

    As Joachim pointed in his answer that the character doesn't consumed by scanf here and lives in the buffer, on next iteration scanf again read the same character and again leave it to the buffer and so on. This results in infinite loop.

    You need to consume this character before next iteration. Just place a getchar() after the line return_value = scanf("%d", &n);

    return_value = scanf("%d", &n);
    while(getchar() != '\n');     // will consume the charater
    

提交回复
热议问题