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 is no 'enter' so to speak.
program -v1 -v2 -v3 <input >output
v1 - v3 are command line arguments respectively
Basically the program spits out the command line arguments and their respective meaning to the program if no 'input' is given and then should exit.
However at the moment if give it an empty test file or just run without pressing enter after running it blocks on the std::getline I use to input the commands.
while(std::getline(std::cin,foo)
{do stuff}
where foo is a string.
How do I get it to just run through and do stuff
at least once then exit in the event of no input? In the event of input the do stuff
occurs once for every line in standard input.
Would a switch to a do-while loop, with a check pre loop as to whether it's got any input, work?
Something like
if cin empty
set flag
do
{do stuff
check flag}
while(getline)
or is non-blocking io not possible in c++?
This question seems to be rehashed over and over but I couldn't find a definitive answer or even an answer that was platform agnostic(this program is academic in nature, coded on windows and tested on unix).
Using std::cin asynchronously might be the only way to make this work, as iostream is not designed to have non-blocking behavior. Here is an example:
The code is commented so it should be easy to understand. It's a thread-safe class that lets you asynchronously get a line using std::cin.
Very easy to use for asynchronous CLI getline purposes, with 0% CPU usage on my computer. It works perfectly well on Windows 10 in Visual Studio 2015 c++ Win32 Console Debug and Release mode. If it doesn't work in your OS or environment, that's too bad.
You can use
cin.peek
to check if there is anything to read, and then callgetline
if there is. There's no such thing as non-blocking getline by itself though.