Q: Reading from stdin without blocking?

J

Jakob Bieling

Hi,

whenever I try to read input from stdin, the called function (ie.
std::cin.read ()) blocks until my buffer is full. But I want to function
to return immediately, regardless of having read something or not. Is
this possible? Here's the tiny code that blocks:

#include <iostream>

int main ()
{
char tmp [64];
std::cin.read (tmp, sizeof tmp);
}


Thank you
 
R

Rolf Magnus

Jakob said:
Hi,

whenever I try to read input from stdin, the called function (ie.
std::cin.read ()) blocks until my buffer is full. But I want to function
to return immediately, regardless of having read something or not. Is
this possible?

No. Not in Standard C++. What you can try is check if something is available
before reading, but it isn't guaranteed to work in all circumstances. It
might or might not on your platform. std::cin.rdbuf()->in_avail() should
(but doesn't need to) return the number of characters available for
reading.
If you want true non-blocking IO, you need to resort to system-specific
functionality.
Here's the tiny code that blocks:

#include <iostream>

int main ()
{
char tmp [64];
std::cin.read (tmp, sizeof tmp);
}


Thank you
 

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,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top