Re: how to check the scanf function if it will read more than one number



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)
.



Relevant Pages

  • setbuf(stdin,NULL) cant work, why?
    ... why does my program work like buffered? ... int main ... c1 = getchar(); ... If the input stream is unbuffered, where does the 'new line' character ...
    (comp.lang.c)
  • Re: getchar() problem
    ... But, when I wrote a program using this function, it looks like the reading of the input stream happens only after I press the ... read the characters as soon as possible. ... int main ... while (ch = getchar()> EOF) ...
    (comp.lang.c)
  • Re: 5^2 =24,10^2=99 ???why???
    ... appropriate to get data from user input due to poor control over data ... Now if again is an int: ... A simple call to getchar() that reads the next character in the ... returns an int and it's better to use the int type for characters read ...
    (comp.lang.c.moderated)
  • Re: printf filestream ?
    ... getchar(), I never get to type anything, it just reads ASCII 10 from ... Better: "int main". ... You probably typed three characters in response to the prompt, ... first two characters plus a newline. ...
    (comp.lang.c)
  • Re: newbie question, fread problem
    ... Also after the first printf I get a newline as expected, ... if I replace int with char then things work like I would expect. ... freadinterprets the input stream in binary. ... to use one of the methods of converting characters to numbers. ...
    (comp.lang.c)