im having an issue with do-while loops, i got input just fine from this site, but im having an issue getting it to accept more than one value as acceptable to pass through the loop.
char MarStat;
do{
std::cout << "Are you Single(S) or Married(M)?\n";
std::cin >> MarStat;
toupper(MarStat);
cout << "Checking...\n";
}while (MarStat == 'M');
works fine but
do{
std::cout << "Are you Single(S) or Married(M)?\n";
std::cin >> MarStat;
toupper(MarStat);
cout << "Checking...\n";
}while (MarStat == 'M' || MarStat == 'S');
doesnt?
and how would i get it to recognize both those so if it gets either, like if it was a switch statment, but confirming the values right after they were entered to see if either one pops up, then continues, not stays in the loop.
Remember that the loop will keep going as long as the condition is TRUE.. Therefore:
}while (MarStat == 'M' || MarStat == 'S');
Will keep looping as long as the input is either M or S (ie: will keep looping as long as the input is valid -- the exact opposite of what you want).
Also... }while (!(MarStat == 'M' || 'S'));
Since 'S' always evaluates to true, the ! makes this expression always evaluate to false, resulting in you NEVER looping, regardless of what the user inputs.
What you want is to loop while the input is invalid... so you'd want something like the following:
char MaritalStatus;
// Ask the user the question
cout << "Are you single or married? " << flush;
while (true)
{
// Get the user's answer.
string s;
cin >> skipws;
if (!getline( cin, s )) break;
// Validate it
if (!s.empty())
{
MaritalStatus = toupper( s[ 0 ] );
if (string( "MS" ).find( MaritalStatus ) != string::npos)
break;
}
// Complain to those who need more instruction
cout << "Enter \"single\" or \"married\": " << flush;
}
// If we get this far, either EOF is encountered or the user input properly
cout << "Good job! Your marital status is '" << MaritalStatus << "'.\n";
So:
Are you single or married? yes
Enter "single" or "married": no
Enter "single" or "married":
Enter "single" or "married": -7
Enter "single" or "married": m
Good job! Your marital status is 'M'.