Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacement of fflush(stdin)

Tags:

c

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.

like image 562
Lijo Avatar asked Nov 30 '22 16:11

Lijo


2 Answers

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.

like image 73
cnicutar Avatar answered Dec 15 '22 06:12

cnicutar


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.

like image 28
Genocide_Hoax Avatar answered Dec 15 '22 04:12

Genocide_Hoax