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
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;
}