Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

c++ - checking data availability before calling std::getline

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 );
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...