alternative to rdbuf()->in_avail()? [was is cin always hte keyboard's input]

B

Bob Smith

so is there any alternative ( standard only ) to using in_avail()?
I need to poll with given intervals the input stream, and if there is
data to be read I want to read it.

thank you
/B
 
T

tom_usenet

so is there any alternative ( standard only ) to using in_avail()?
I need to poll with given intervals the input stream, and if there is
data to be read I want to read it.

There is no C++ standard alternative. There are POSIX standard and
Win32 ways of doing it (O_NONBLOCK, select, WaitFor*), and no doubt
other platforms have similar functionality.

Note that if you use select, you should also use in_avail. After
select has notified you of some waiting input, you should read a
character, and then keep reading characters until in_avail is 0. e.g.

//OS has said that characters are waiting on stdin (via select, say)

std::vector<char> input;
char c;
cin.get(c); //this may cause a load of characters to be buffered
input.push_back(c);
//we now need to empty the buffer so that select will work next time
while(cin.rdbuf()->in_avail() > 0){
if (!cin.get(c))
{
//error
}
input.push_back(c);
}

//now ask OS again whether characters are waiting.



If you use a non-blocking stream, then this is the way:

// maybe there are characters waiting, maybe not

std::vector<char> input;
char c;
while(cin.get(c))
{
input.push_back(c);
}
//no more waiting.

if (cin.bad())
{
//error
}
//get cin ready for next time by clearing eof flag
cin.clear();

Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top