How to handle exception when scanf of integer gets a character

后端 未结 4 395
南笙
南笙 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:22

    You get an infinite loop because scanf doesn't consume the character, so the character will never leave the input buffer.

    You can solve it by reading a line with e.g. fgets and then use sscanf on the line.

提交回复
热议问题