Problem with [Y/N] option in console.

Hi guys,

I am not sure how to describe this problem, so I'll just keep it simple.
In my console app, users can choose if they want to exit the program or not by entering 'Y' or 'N'.
This works fine, but whenever the user enters more characters, it starts to act weird.
For example, if a user enters 'hello' where he/she should've put 'Y' or 'N', the output is as follows:

Would you like to exit the program? [N/Y]
Option: hello
Invalid option - please enter a valid value. Variable holds: h
Would you like to exit the program? [N/Y]
Option: Invalid option - please enter a valid value. Variable holds: e
Would you like to exit the program? [N/Y]
Option: Invalid option - please enter a valid value. Variable holds: l
Would you like to exit the program? [N/Y]
Option: Invalid option - please enter a valid value. Variable holds: l
Would you like to exit the program? [N/Y]
Option: Invalid option - please enter a valid value. Variable holds: o
Would you like to exit the program? [N/Y]
Option:


The code is as follows:

1
2
3
4
5
6
7
8
9
10
	end:
	std::cout << "Would you like to exit the program? [N/Y]\n";
	char exit;
	std::cout << "Option: ";
	std::cin >> exit;
	if (exit == 'y') { return 0; }
	else if (exit == 'n') { goto keyoption; }
	else {
	std::cout << "Invalid option - please enter a valid value. Variable holds: " << exit << "\n";
	goto end;


Any suggestions on how to fix this?
Thanks in advance.
Last edited on
first of all why do you use goto?
a simple do-while, or even while, loop should do the job perfectly.
1
2
3
4
5
6
char exit;
do{
cin>>exit;
if(exit!='y')
cout<<"wrong option"<<endl;
}while(exit=='y')

and if its a "no" i advise making another subroutine and linking it to the main programm inside the loop.
Last edited on
Thank you guys so much, a simple std::cin.sync(); did the trick.

@jimas13; I am using goto because I just started C++ last night, I know very little about it so far. Thanks for the advice, tho.
What are you learning C++ from that teaches goto instead of loops?
I used goto since I started scripting in mIRC. But I am familiar with while, I just never used do-while before.
For security reasons, do not ever use goto's in C++.
Thanks, I will remember that.
I will try to find another way to jump to other parts of the code.
The most common way of jumping to other parts of code are "functions". We also use loops ( for, while, and do-while ) and branches (if, switch).
Topic archived. No new replies allowed.