non-blocking std::getline, exit if no input

后端 未结 3 1049
遇见更好的自我
遇见更好的自我 2021-01-11 11:51

Currently I have a program that reads from the standard input, occasionally the program needs to just keep running if no input is made, usually this is a test script there i

3条回答
  •  孤独总比滥情好
    2021-01-11 12:34

    You can make a non-blocking equivalent to std::getline fairly easily using the istream::readsome() method. This reads available input up to a maximum buffer size, without blocking.

    This function will always return instantly, but will capture a line if one is available on the stream. Partial lines are stored in a static variable until the next call.

    bool getline_async(std::istream& is, std::string& str, char delim = '\n') {
    
        static std::string lineSoFar;
        char inChar;
        int charsRead = 0;
        bool lineRead = false;
        str = "";
    
        do {
            charsRead = is.readsome(&inChar, 1);
            if (charsRead == 1) {
                // if the delimiter is read then return the string so far
                if (inChar == delim) {
                    str = lineSoFar;
                    lineSoFar = "";
                    lineRead = true;
                } else {  // otherwise add it to the string so far
                    lineSoFar.append(1, inChar);
                }
            }
        } while (charsRead != 0 && !lineRead);
    
        return lineRead;
    }
    

提交回复
热议问题