fflush() is not working in Linux

前端 未结 9 786
后悔当初
后悔当初 2020-12-08 05:43

I used the fflush() in Linux GCC but it did not work. Are there any alternatives for that function? Here is my code:

#include
void main()
{
           


        
相关标签:
9条回答
  • 2020-12-08 06:18

    Don't use fflush, use this function instead:

    #include <stdio.h>
    void clean_stdin(void)
    {
        int c;
        do {
            c = getchar();
        } while (c != '\n' && c != EOF);
    }
    

    fflush(stdin) depends of the implementation, but this function always works. In C, it is considered bad practice to use fflush(stdin).

    0 讨论(0)
  • 2020-12-08 06:18

    The behavior of fflush is not defined for input streams (online 2011 standard):

    7.21.5.2 The fflush function

    Synopsis

    1
    
        #include <stdio.h>
        int fflush(FILE *stream);
    
    Description

    2 If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

    3 If stream is a null pointer, the fflush function performs this flushing action on all streams for which the behavior is defined above.

    Returns

    4 The fflush function sets the error indicator for the stream and returns EOF if a write error occurs, otherwise it returns zero.
    0 讨论(0)
  • 2020-12-08 06:19

    fflush() doesn't do much for input streams but since scanf() never returns this doesn't matter. scanf() blocks because the terminal window doesn't send anything to the C program until you press Enter

    You have two options:

    1. Type 10 Enter
    2. Put the terminal into raw mode.

    The second option has many drawbacls like you will lose editing capabilities, so I suggest to read the input line by line.

    0 讨论(0)
  • 2020-12-08 06:20

    By using bzero(); system call in Linux we can flush the previous stored value.
    Please read the manual page of bzero(); by typing in terminal man bzero. try this example

    #include<stdio.h>
    #include<string.h>
    
    int main()
    {
      char buf[]={'y'};
      int num;
      while(buf[0]=='y')
      {
        printf("enter number");
        scanf("%d",&num);
        printf("square of %d is %d\n",num,num*num);
        bzero(buf, 1);
        printf("want to enter y/n");
        scanf("%s",&buf[0]);
      }
      return 0;
    } 
    
    0 讨论(0)
  • 2020-12-08 06:33

    I faced the same problem while working on LINUX and an alternative solution of this problem can be that you define a dummy character lets say char dummy; and put a scanf() to scan it just before your actual input takes place. This worked for me. I hope it would work for you too.

    0 讨论(0)
  • 2020-12-08 06:40

    You must include and use __fpurge(whatever you want) instead.

    Salute from argentina

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