I ask a person to enter in if they're male or female by typing m or f, but if they type something other than M, m, F, or f I want and an error message to happen and have them try again. The problem is the program continues on whether or not the correct character was typed in. How do you start the if statement over until the right character is typed in?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
cout << "Gender (M or F): " << endl;
cin >> gender;
if(gender == 'M' || gender == 'm'){
gender = 8;
}
elseif(gender == 'F' || gender == 'f'){
gender = 10;
}
else{
cout << "Not a valide answer" << "Please enter M for male or F for female" << endl;
}
Oh sorry. It is because my do while loop is checking for "m" and "f" not 8 or 10 as the variables you set. You will have to update that so it says to do the loop while gender != 10 or 8.
Also, is your gender variable a char or an int? you can't have it be 'm' and then set it to 8.
You'll want to put the do { before it prompts the user. Otherwise it just keeps looping back to check the input to see if it changes, and since it won't change (because the loop doesn't prompt the user to change it) it will keep going forever.
You also won't need to prompt the user for a second time since it will fail and start from the do { again.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <string>;
#include <iostream>;
usingnamespace std;
void main()
{
string inputVar = "";
do
{
cout << "enter the letter m: ";
getline (cin,inputVar);
}
while (inputVar != "m");
cout << "Exited loop";
system("pause");
}
well I still can't get out of the loop. It starts back at the start and the user can input new letters, but if the right letter is typed the loop still loops.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
while(gender != 'm' || 'M' || 'f' || 'F'){
cout << "Gender (M or F): " << endl;
cin >> gender;
if(gender == 'M' || gender == 'm'){
gender = 8;
}
elseif(gender == 'F' || gender == 'f'){
gender = 10;
}
else{
cout << "Not a valide answer" << endl <<
"Please enter M for male or F for female" << endl;
}
}
if (gender == 'M' || gender == 'm')
{
person = 8;
break;
}
that will break you out of the loop. I think part of the issue is you are using cin and never convert the users input to a char. Sorry I'm a beginner myself so i'm working it through with you :)
Okay, you're right about the semicolon; however, the while I used makes sense.
while(person != 8 && person != 10)
It's saying while "person" is not equal to 8 and "person" is not equal to 10, continue to loop.
Once person is equal to 8, the loop will terminate because it is now equal to 8. Both conditions need to be met for the loop to continue. Once "person" becomes equal to either 8 or 10, the loop will terminate.