int main ()
{
int wordCode;
const int QUIT_MENU = 9;
Menu
do
{
cout << "Given the phrase:" << endl;
cout << "Now is the time for all good men to come to the aid of their ___.\n" << endl;
cout << "Input a 1 if you want the sentence to be finished with party." << endl;
cout << "Input any other number for the word country.\n" << endl;
cout << "Please input your choice now." << endl;
cin >> wordCode;
cout << endl;
writeProverb(wordCode);
while (wordCode >= 1 || wordCode <= 2)
{
cout << "You have not entered a valid selection." << endl;
cout << "Please eneter a 1 or a 2." << endl;
}
if (wordCode != QUIT_MENU)
{
switch (wordCode)
{
case 1:
writeProverb(wordCode);
break;
case 2:
writeProverb(wordCode);
}
}
Is the proper way to exit this loop?
}while (wordCode != QUIT_MENU);
return 0;
}
Start of void function to write proverb.
void writeProverb (int wordCode)
{
//Fill in the body of the function to accomplish what is described above
if (wordCode == 1)
{
cout << "Now is the time for all good men to come to the aid of their party." << endl;
}
if (wordCode == 2)
{
cout << "Now is the time for all good men to come to aid the aid of their country." << endl;
}
}
"You have not entered a valid selection." "Please eneter a 1 or a 2."
The above text keeps repeating no matter what value is selected.
Why should it?
while (wordCode >= 1 || wordCode <= 2)
User enters:
wordCode >= 1 wordCode <= 2
1 True True -> True || True -> True
-1 False True -> False || True -> True
2 True True -> True || True -> True
3 True False -> True || False -> True
999999 True False -> True || False -> True
-99999 False True -> False || True -> True
no matter what number the user enters, the condition can literally never become false.
Change
while (wordCode >= 1 || wordCode <= 2)
to
if (wordCode == 1 || wordCode == 2)
You don't want that part to loop; the outer do/while
handles that just fine. You just need to output the message once.
要添加到马克·B的答案中,我想您需要while (wordCode == 1 || wordCode == 2)
Change "while (wordCode >= 1 || wordCode <= 2)" to "while (wordCode >= 1 && wordCode <= 2)". That should fix your loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.