0

我正在为代码编写一个执行菜单。它使用 switch 语句。我的问题是关于while。我需要代码仅在用户输入大写 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;
4

2 回答 2

3

一是条件choice != 'F' || 'f'不对。正确的条件是((choice != 'F') && (choice != 'f'))

对于小写字母,您可以在while循环中使用此条件:

while (! ((choice >= 'a' && choice <= 'f') || (choice >= 'A' && choice <= 'F')))

或使用toupper/tolower功能来自ctype.h

于 2013-10-19T19:21:44.687 回答
0

版本 1

while ( (choice < 'a' || choice > 'f') && (choice < 'A' || choice > 'F') )

版本 2

while(choice < 'A' && choice > 'F')
{
    std::cin>>choice;
    choice = toupper(choice);
}

希望有帮助

于 2013-10-19T21:00:04.317 回答