I am not able to flush stdin

后端 未结 7 1785
孤城傲影
孤城傲影 2020-11-22 14:51

How to flush the stdin??

Why is it not working in the following code snippet?

#include 
#include 
#i         


        
相关标签:
7条回答
  • 2020-11-22 14:56

    You can't clean stdin in Linux without bumping into scenarios that the command will start waiting for input in some cases. The way to solve it is to replace all std::cin with readLineToStdString():

    void readLine(char* input , int nMaxLenIncludingTerminatingNull )
    {
        fgets(input, nMaxLenIncludingTerminatingNull , stdin);
    
        int nLen = strlen(input);
    
        if ( input[nLen-1] == '\n' )
            input[nLen-1] = '\0';
    }
    
    std::string readLineToStdString(int nMaxLenIncludingTerminatingNull)
    {
        if ( nMaxLenIncludingTerminatingNull <= 0 )
            return "";
    
        char* input = new char[nMaxLenIncludingTerminatingNull];
        readLine(input , nMaxLenIncludingTerminatingNull );
    
        string sResult = input;
    
        delete[] input;
        input = NULL;
    
        return sResult;
    }
    

    This will also allow you to enter spaces in std::cin string.

    0 讨论(0)
  • 2020-11-22 14:59
    int c;
    while((c = getchar()) != '\n' && c != EOF);
    

    Is how I'd clear the input buffer.

    0 讨论(0)
  • 2020-11-22 15:00

    From the comp.lang.c FAQ, see:

    • How can I flush pending input so that a user's typeahead isn't read at the next prompt? Will fflush(stdin) work?
    • If fflush won't work, what can I use to flush input?
    0 讨论(0)
  • 2020-11-22 15:05

    You are overriding the last element of the input in arg with '\0'. That line should be arg[i]='\0'; instead (after error and boundary checking you are missing.)

    Other's already commented of the flushing part.

    0 讨论(0)
  • 2020-11-22 15:07

    In Windows you can use rewind(stdin) fuction.

    0 讨论(0)
  • 2020-11-22 15:13

    How to flush the stdin??

    Flushing input streams is invoking Undefined Behavior. Don't try it.

    You can only flush output streams.

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