Auto press enter in cin?

Hi guys

I saw a program that asks the user to input y or n to continue the process... and when you input one of them it automatically presses enter and proceed to the next process

I want to know how to do that .. and can I manage the number of digits or characters to be taken before auto pressing enter?

Thanks
It doesn't automatically press enter. It's using a different (non-portable) method of key entry.

What environment (Operating System, compiler/dev environment) are you using?
Windows 7 .. C++ and visual studio

how to do it?
1
2
3
4
char answer; 
cout << "would you like to continue: [y/n] ";
cin >> answer;
if (answer != 'y') exit (0);


or if u want string to be used for answer replace char with char* or string.
simple :)
Last edited on
you need to press enter in order to put y or n inside answer variable
but what I want is... you don't need to press enter .. it should press enter automatically after you press y or n.

thanks
One way to do this is to use the _getch() function from the conio.h header file. Here is an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <conio.h> //this header is needed to use _getch()

using namespace std;

int main () {
	cout << "Do you want to see the secret word? (y/n): ";
	char move = _getch(); //_getch loads move with one character that the user enters
			      //the code continues after one key is pressed
		if(move == 'y') {
			cout << "\nThe secret word is chicken burger!" << endl;
		}
		else if(move == 'n') {
			cout << "\nWhy didn't you want to see the secret word?" << endl;
		}
		else {
			cout << "\nInvalid input." << endl;
		}
		return 0;
}
Last edited on
Thank you very much!!
is there anyway to make it take 2 numbers or characters?

thanks again
Last edited on
If you want an option after another option, try using a switch statement.

Use the code above, then re-use the code within the switch statement to get input once again, but for another option. Or just get the switch statement to call a function with the above code in to get more input.

http://cplusplus.com/doc/tutorial/control/#switch
Topic archived. No new replies allowed.