Will Klingelsmith
Will Klingelsmith

Reputation: 153

Bypassing blocking input stream with C++/Boost

I'm currently writing something of a quiz program. This program throws questions at the user until a specified time limit runs out. How it's set up now is the quizzing functionality runs in a boost thread and the timing aspect is handled by a timed_join() on that thread. The problem I'm encountering is when the user is answering a question using cin, the thread will go past the time limit that has been established. Is there a way to have it interrupt the cin call?

Upvotes: 4

Views: 486

Answers (3)

Steve Townsend
Steve Townsend

Reputation: 54148

You can use Boost.Asio to read from cin asynchronously as described here - updated link to example code is here.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409176

You might need to use other input methods. The readline library might be able to help you. Or if you are on Linux, you can go down to pure file descriptors, make STDIN_FILENO non-blocking like a non-blocking socket and use the select system-call and then you can get both the timeout and know when input is ready.

Upvotes: 0

Kiril
Kiril

Reputation: 40345

You can read the input character by character in a non-blocking read by using getchar, getch or getche. If you've been looping long enough to reach the timeout, then stop looping :).

Upvotes: 2

Related Questions