Mail Archives: djgpp/2003/09/08/10:01:25
Ethan Rosenberg wrote:
>
> Pardon me for askiing a question which might be trivial, but I am
> stumped. I have a program with multiple fgets() in sequence; ie
>
> fgets(mr, 9, stdin);
> .do something ....
> fgets(ga, 9, stdin);
> . do something ...
> .
> .
> .
> If the user types more than 8 characters, the remaining characters
> are left in the keyboard(?) buffer, and are picked up by the next
> fgets. How do I get rid of the remaining characters, before the
> following fgets.
First, check the return value of fgets against NULL. If equal,
you have an i/o error or EOF. Then check the last char of the
input string. If it is '\n' you have a complete line, if not you
can flush the input line with something like:
while ((EOF != (ch = getc(stdin)) && (ch != '\n'}) continue;
So the overall code will look something like:
if (fgets(mr, 9, stdin)) {
do something that doesn't alter mr;
if ('\n' != mr[strlen(mr)-1)) {
flushln(stdin);
}
}
where flushln calls the above suggested code embedded in a
function. (ch must be an int). It could also return "EOF == ch"
to enable the caller to detect EOF.
Another solution is to use ggets, which is freely available at:
<http://cbfalconer.home.att.net/download/>
--
Replies should be to the newsgroup
Chuck Falconer, on vacation.
- Raw text -