我正在为代码编写一个do-while菜单。它使用switch语句。 我问的问题是而。我需要代码只在用户输入大写A - F或小写a - f时运行。现在,while语句只适用于大写。我不知何故需要让它适用于小写。
以下是代码:
//display menu
do
{
cout << "A. Get the number of values entered \n"
<< "B. Get the sum of the vaules \n"
<< "C. Get the average of the values \n"
<< "D. Get the largest number \n"
<< "E. Get the smallest number \n"
<< "F. End the program \n"
<< "Enter your choice: ";
cin >> choice;
while (choice < 'A' || choice >'F')
{
cout << "Please enter a letter A through F: ";
cin >> choice;
}
if (choice != 'F' || 'f')
{
switch (choice)
{
case 'A':
case 'a': cout << "Number of numbers is: " << numCount << endl;
break;
case 'B':
case 'b': cout << "Sum of numbers is: " << sum << endl;
break;
case 'C':
case 'c': cout << "Average of numbers is: " << average << endl;
break;
case 'D':
case 'd' : cout << "Max of numbers is: " << max << endl;
break;
case 'E':
case 'e': cout << "Min of numbers is: " << min << endl;
break;
default: cin >> c;
}
}
else
{
cin >> c;
}
}
while (choice !='F' || 'f');
return 0;
答案 0 :(得分:3)
首先,条件choice != 'F' || 'f'
是错误的。
正确的条件是((choice != 'F') && (choice != 'f'))
。
对于小写的工作,您可以在while
循环中使用此条件:
while (! ((choice >= 'a' && choice <= 'f') || (choice >= 'A' && choice <= 'F')))
或使用toupper
tolower
/ ctype.h
个功能
答案 1 :(得分:0)
版本1
while ( (choice < 'a' || choice > 'f') && (choice < 'A' || choice > 'F') )
第2版
while(choice < 'A' && choice > 'F')
{
std::cin>>choice;
choice = toupper(choice);
}
希望有所帮助