How to check when the user presses a key

Ok, part of my console program gets the user to press enter to continue after reading the introduction of how to use the program.

I've halted the program using the code below:
1
2
cout << "Please press ENTER to continue.";
cin.get();

But when in the console I can still enter letters or whatever when I type on the keyboard. Is there anyway I can stop the user from entering anything but pressing the enter key?

Thanks, SoftMount.
i guess the easiest way is to use the windows specific header & function, conio.h & getch()
( usually included in mingw compiler & i think it's available in VS )

1
2
3
4
5
6
7
8
#include <cstdio>
#include <conio.h> // windows only

int main()
{
    puts( "Press ENTER to continue..." );
    while( getch() != '\r' ) ;
}
Last edited on
Thank you it worked!

Just a quick question, as Im still a Beginner could you explain how your code above works? What is thegetch(); function and why you need to use the while loop.

I just like to know how the code works before I use it in my program, as if I don't understand it, why use it.

Thank you.

Also, I am using MS VS and it told me to use _getch() instead of getch()
Last edited on
Conio.h is deprecated, we strongly recommend you do not use it:
https://en.wikipedia.org/wiki/Conio.h

See this thread:
http://www.cplusplus.com/forum/beginner/1988/
getch() gets a single character from the console but doesn't print or echo it, it then returns the value it read.

The while part can be read as : "while the value returned by getch() is not equal (!=) to ('\r') (carriage return), then keep executing the loop"

The condition in the while loop becomes false if the value returned by getch is equal to '\r' and thus ends the loop.

i don't know why VS precedes it w/ underscore

and yes, conio.h is depracated & non standard
Last edited on
Topic archived. No new replies allowed.