Why does scanf appear to skip input?

前端 未结 7 1531
忘了有多久
忘了有多久 2020-12-19 13:17

I am confused about scanf\'s behaviour in the following program. scanf appears to input once, and then not input again, until a stream of characters is printed.

Belo

7条回答
  •  -上瘾入骨i
    2020-12-19 14:08

    If scanf sees a character in the input stream that doesn't match the conversion specifier, it stops the conversion and leaves the offending character in the input stream.

    There are a couple of ways to deal with this. One is to read everything as text (using scanf with a %s or %[ conversion specifier or fgets) and then use atoi or strtol to do the conversion (my preferred method).

    Alternately, you can check the return value of scanf; it will indicate the number of successful conversions. So, if scanf("%d", &i); equals 0, then you know there's a bad character in the input stream. You can consume it with getchar() and try again.

提交回复
热议问题