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

后端 未结 3 1826
北荒
北荒 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 15:14

    There are 2 separate issues. The first is something I'd call flow control. In situations where the "sender" (e.g. a fast typist using a console application) sends data faster than the "receiver" (e.g. slow console application software) can receive it, you do not want to lose data and do want to have a buffer to prevent data loss.

    For a simple example, if your lecturer is as smart as they should be, they'll probably make their own life easier by using automated script to pre-test student's assignments. In this case STDIN would actually be a file (and data from STDOUT would be checked to see if it matches an expected pattern). By discarding everything in STDIN you'd discard all input and fail.

    The second issue is keeping the application synchronised with its input. This is normally done by fetching a line of user input (then parsing it and doing something with the parsed data), then fetching the next line, etc. If you do this wrong (e.g. only fetch part of a line of input) then you need to find a way to handle any characters between the end of what you fetched and the end of the line. The simple solution here is don't do it wrong to begin with - e.g. use a "fetch entire line of user input" function (maybe gets()) and worry about parsing the line of user input after you've obtained it.

    Also note that sane software will handle unwanted/unexpected characters by generating some sort of an "unknown characters after ..." error message, not by discarding/ignoring them. It's best to do this during parsing, not after parsing when you're doing something with data from (probably wrong) user input. For a simple example, imagine "enter your age: 22 months" - in this case you're expecting the user to enter years, you see "22" then see "months" then generate an error ("Bad input - please enter 'age' as a single number of years"). You don't just assume the user wanted 22 years.

提交回复
热议问题