Clearing out stdin in C when it may or may not be empty

后端 未结 3 1903
北荒
北荒 2021-01-22 14:38

I am a programming student looking for a way to get rid of characters that may be hanging around in stdin. I have tried a technique that has been given here in various forms, wh

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-22 14:52

    There is no portable way of doing this, since the standard input is "blocking" by default you can't read from it in order to throw the input away without causing a block if there was no input.

    If you have it, you can use select() to detect that there is input, and then do a read to discard it. I would recommend doing a "large" block read in that case, not a single character at a time.

    Please note that getchar() returns int, the constant EOF does not fit in a character. It's an example of "out of band" communication, it's not a character.

提交回复
热议问题