Problem with [Y/N] option in console.

Mar 25, 2012 at 9:35pm
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 Mar 25, 2012 at 9:36pm
Mar 25, 2012 at 9:39pm
Mar 25, 2012 at 9:43pm
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 Mar 25, 2012 at 9:45pm
Mar 25, 2012 at 9:57pm
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.
Mar 25, 2012 at 10:17pm
What are you learning C++ from that teaches goto instead of loops?
Mar 25, 2012 at 10:31pm
I used goto since I started scripting in mIRC. But I am familiar with while, I just never used do-while before.
Mar 25, 2012 at 10:35pm
For security reasons, do not ever use goto's in C++.
Mar 25, 2012 at 10:40pm
Thanks, I will remember that.
I will try to find another way to jump to other parts of the code.
Mar 25, 2012 at 10:59pm
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.