Replacement of fflush(stdin)

后端 未结 3 533
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 22:19

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

相关标签:
3条回答
  • 2020-11-27 22:24

    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.

    0 讨论(0)
  • 2020-11-27 22:34
    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.

    0 讨论(0)
  • 2020-11-27 22:43

    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.

    0 讨论(0)
提交回复
热议问题