I am trying to get the user to enter yes(y) or no(n). If they enter neither of those, then I want it to say "guess again", and I used the goto function to do this. The problem is that it keeps looping through as if the user keeps pressing a letter besides y or n.
#include <iostream>
#include <string>
#include <cstdlib>
usingnamespace std;
int main()
{
char yn;
cout << "Is this correct (press y for yes or n for no): ";
cin >> yn;
PickAgain:
if (yn == 'y')
cout << "Ok! I randomly choose... ";
if (yn == 'n')
cout << "Do";
if (yn != 'n' || yn != 'y')
{
cout << "That is not an option, dumbass. Pick again.";
goto PickAgain;
}
return 0;
}
Use while, do-while or other control statements. For example
1 2 3 4 5 6 7 8 9 10 11 12 13 14
char yn;
do
{
cout << "Is this correct (press y for yes or n for no): ";
cin >> yn;
if (yn == 'y')
cout << "Ok! I randomly choose... ";
elseif (yn == 'n')
cout << "Do";
else
cout << "That is not an option, dumbass. Pick again.";
} while ( yn != 'y' && yn != 'n' );
Or instead of if-else you can use switch inside the loop
char yn;
do
{
cout << "Is this correct (press y for yes or n for no): ";
cin >> yn;
switch ( yn )
{
case'y': case'Y':
cout << "Ok! I randomly choose... ";
break;
case'n': case'N':
cout << "Do";
break;
default:
cout << "That is not an option, dumbass. Pick again.";
break;
}
} while ( yn != 'y' && yn != 'n' );
While it is bad practice to use goto statements, there are certain situations where they come in handy. Your problem isn't a problem with the goto at all. To fix your program, do this:
#include <iostream>
#include <string>
#include <cstdlib>
usingnamespace std;
int main()
{
char yn;
cout << "Is this correct (press y for yes or n for no): ";
PickAgain:
cin >> yn;if (yn == 'y')
cout << "Ok! I randomly choose... ";
elseif (yn == 'n')
cout << "Do";
elseif (yn != 'n'&& yn != 'y')
{
cout << "That is not an option, dumbass. Pick again.";
goto PickAgain;
}
return 0;
}