Re: how to check the scanf function if it will read more than one number
- From: Richard Heathfield <invalid@xxxxxxxxxxxxxxx>
- Date: Mon, 2 Jan 2006 13:12:41 +0000 (UTC)
moosdau said:
<snip>
> [...] I don't know very clearly why shouldn't I use the fflush function.
> if there is not any usable data in the input stream,
Because fflush's behaviour is only defined for streams open for output or
update.
> could I use it to clear the input stream?
Not as far as the C language is concerned, no.
> if not , could you please tell me why?
For the same reason that pressing the handle on your toilet will not get rid
of the water waiting in your sink's tap (or faucet, if you're on that side
of the pond). Flushing is something we do to output, not to input.
If you want to discard from stdin everything up to and including a
particular character, you can use this function:
#include <stdio.h>
int DiscardFromStream(FILE *fp, int lim)
{
int ch;
while((ch = getc(fp)) != lim && ch != EOF)
{
continue;
}
return ch == EOF;
}
/* example usage */
int main(void)
{
int ch;
puts("Type a letter, and press ENTER.");
ch = getchar();
if(0 == DiscardFromStream(stdin, '\n'))
{
printf("You pressed %c\n", ch);
puts("Type another letter, and press ENTER.");
ch = getchar();
if(0 == DiscardFromStream(stdin, '\n'))
{
printf("You pressed %c\n", ch);
}
}
return 0;
}
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
.
- Follow-Ups:
- References:
- Prev by Date: Re: String reversing problem
- Next by Date: Re: String reversing problem
- Previous by thread: Re: how to check the scanf function if it will read more than one number
- Next by thread: Re: how to check the scanf function if it will read more than one number
- Index(es):
Relevant Pages
|
|