I would like to read some data from a stream I have using std::getline
. Below a sample using the std::cin
.
std::string line; std::getline( std::cin, line );
This is a blocking function i.e. if there is no data or line to read it blocks execution.
Do you know if exists a function for checking data availability before calling std::getline
? I don't want to block.
How can I check whether the stream buffer is full of data valid for a successful call to std::getline
?
Whatever looks like the code below
if( dataAvailableInStream() ) { std::string line; std::getline( std::cin, line ); }
The getline() function in C++ is used to read a string or a line from the input stream. The getline() function does not ignore leading white space characters.
getline (string) in C++ The C++ getline() is a standard library function that is used to read a string or a line from an input stream. It is a part of the <string> header. The getline() function extracts characters from the input stream and appends it to the string object until the delimiting character is encountered.
The main difference between getline and cin is that getline is a standard library function in the string header file while cin is an instance of istream class. In breif, getline is a function while cin is an object. Usually, the common practice is to use cin instead of getline.
std::getline will read up to and including the final newline character and then return. It won't attempt to read beyond the end of the file. The EOF bit won't be set. If we are conditioned on eof() , we will start another iteration with nothing left to read.
There is no standard way to verify if getline
will block. You can use:
std::cin.rdbuf()->in_avail()
to see how many characters are definitely available before a read operation may block, but you would have to read the characters one by one before re-checking in_avail
as there is no way to know in advance if any of the pending characters is a newline or the actual end of the stream. A getline
call might block if this wasn't the case.
Note that although if in_avail()
returns a postive number there are guaranteed that at least that many characters are available before the end of the stream, the converse is not true. If in_avail()
returns zero there may still be characters available and the stream might not block immediately.
The iostream
library doesn't support the concept of non-blocking I/O. I don't think there's anything in the C++ standard that does. Any good solution would likely be platform-specific. If you can use the POSIX libraries, you might look into select
. It's usually used for networking stuff, but it'll work just fine if you pass it the file descriptor for stdin.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With