I am not able to flush stdin

后端 未结 7 1962
孤城傲影
孤城傲影 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.

提交回复
热议问题