4

I have the below code,

fflush(stdin);
print("Enter y/n");
scanf("%c",&a);

Here,it is quitting before giving the input.it looks like the issue is because it is not flushing out the input buffer which might be having some junk characters.Is there any alternative for flush(stdin).This code snippet is working in Solaris but it is not working in Linux.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Lijo
  • 41
  • 1
  • 1
  • 2
  • 3
    First line of `man fflush` reads: *The function `fflush()` forces a **write** of all user-space buffered data for the given **output or update** stream*. cnicutar has the right answer for how to skip unwanted input, but in addition to that you *should* read the docs of the functions you're using. *And* check their return value... as your call above will have returned `EOF` and set `errno = EBADF` to signal your wrongful use of the function. Ignoring return values is bad, bad, bad... – DevSolar Jun 08 '11 at 10:57
  • See also [Using `fflush(stdin)`](http://stackoverflow.com/questions/2979209/using-fflushstdin). – Jonathan Leffler Sep 15 '16 at 05:31

3 Answers3

16

This is well explained in the C FAQ. See also: explanation. The proposed solutions:

  • Quit using scanf. Use fgets and the sscanf
  • Use this to eat the newline

    while((c = getchar()) != '\n' && c != EOF)
    /* discard the character */;
    

The fact that flushing stdin works on some implementations is wrong.

Some vendors do implement fflush so that fflush(stdin) discards unread characters, although portable programs cannot depend on this.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
3

For C on GNU

you can use



__fpurge(stdin);

include stdio_ext.h header for accessing the function. Though the post is very old still I thought this might help some linux developers.

Genocide_Hoax
  • 843
  • 2
  • 18
  • 42
  • This is horrible, even if it works as intended. Imagine what happens if the input is coming from a file or a pipe. – Rafael Lerm Jan 17 '15 at 23:51
2
scanf(" %c",&c);

or

scanf(" ");
//reading operation (gets(), fgets(stdin,...) etc)

Spaces in the scanf() format string will ignore any whitespace until the first non-whitespace.

humodz
  • 600
  • 3
  • 8