3

A similar question for Python was asked.

How to ignore user input during sleep in Python 3?

How would I do that in C++? I am using this sleep command, and would prefer to keep using it.

this_thread::sleep_for(chrono::seconds(4));

However, it still will collect user input, which causes the user to miss important text they skip over. How can I prevent this?

Input as in Keyboard input using:

_getch();

This is a console application.

cout << "Wait 4 Seconds";
this_thread::sleep_for(chrono::seconds(4));
cout << "More text here!";
cout << "\n Press any key to go on";
_getch();

AFTER ANSWER EDIT Final Code would look like this:

cout << "Wait 4 Seconds";
this_thread::sleep_for(chrono::seconds(4));
while (_kbhit())
{_getch();}
cout << "More text here!";
cout << "\n Press any key to go on";
_getch();
Jerry Jeremiah
  • 9,045
  • 2
  • 23
  • 32
majneeds2chill
  • 93
  • 1
  • 10
  • 2
    User input from what? Keyboard? Mouse? GUI? Miss important text how? – user207421 Dec 30 '15 at 03:54
  • What input code are you using? have you tried? single char at a time? or getline? These should make a difference. – 2785528 Dec 30 '15 at 03:55
  • Just flush the input immediately after the call to `sleep_for` returns. – Captain Obvlious Dec 30 '15 at 03:57
  • If your app is all one thread, then when that thread sleeps, nothing else will take place. – seand Dec 30 '15 at 04:02
  • I don't know how POSIX-compliant MS Windows's POSIX emulation is. On a POSIX-compliant platform, this is done by temporary setting standard input to non-blocking, draining all input (in your case, via your _getch() function), then resetting standard input to blocking. – Sam Varshavchik Dec 30 '15 at 04:15

1 Answers1

3

After sleeping, you can...

while (kbhit())
    getch();

This sees if there's input waiting, and if so call getch() to discard a character. Rinse and repeat.

God knows how MS name their functions, but if you can't find kbhit() try _kbhit() from <conio.h>.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252