• 0

[C++] Console function to wait for input


Question

This has annoyed me for hours if not days. :(

I'm writing a simple console application with a menu that has some choices. Every time you select an option it should:

ask for a number,

output the result,

pause the app until a key is pressed so the user can read the data printet out,

clear the screen and display the menu again

system("pause") doesn't work because it's launched in a seperate thread and is not in sync with the application (sometimes its way behind the app and sometimes ahead of the execution(!) O_o )

SleepEx() doesn't seem to be able to do what I want.

WaitForInputIdle() doesn't work since console applications doesn't have a message queue.

What can I do to make this work? I hate those system calls to be so out of sync with the app!

And no, I don't want to use an infinite while loop untill a char is pressed as it would take 100% CPU.

Anyone? :(

Edited by Andos
Link to comment
https://www.neowin.net/forum/topic/462358-c-console-function-to-wait-for-input/
Share on other sites

7 answers to this question

Recommended Posts

  • 0

It just seems that EVERYTHING is completely out of sync when doing those console apps.

I was just told to use the getchar(); function to wait for an enter press.

I have this code:

------

cout << "Press enter to continue...";

getchar();

------

For whatever reason, it waits for the enter key and THEN it prints out "Press enter to continue..." :s

What is wrong here???

  • 0

If you're on Windows some functions from conio.h may work for you

http://www.digitalmars.com/rtl/conio.html

(This is non-standard and will make your code less portable)

If things are "out of sync" try to flush your output after you print.

printf("Press enter to continue...");
fflush(stdout);
getchar();

Are you sure you don't have another input routine before your "Press enter..." that is waiting for input?

Edited by spydoor
  • 0

Thanks but that didn't work.

But I'm using cout << and not printf()

How come such a simple app can have so many problems with this? And why has so few gotten theese issues before?

:-/

*edit*

Yes i have a cin >> somevalue; input a bit earlier in the code.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.