John DAngelo
John DAngelo

Reputation: 15

C++ Do-While loop for Menu. Testing both uppercase and lowercase:

I'm writing a do-while menu for a code. It uses a switch statement. The question I have regards the while. I need the code to only run when the user enters uppercase A - F, or lowercase a - f. Right now, the while statement only works with uppercase. I somehow need to make it work for the lowercase as well.

Here's the code:

//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;

Upvotes: 0

Views: 6477

Answers (2)

Bozemoto
Bozemoto

Reputation: 226

Version 1

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

Version 2

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

Hope that helps

Upvotes: 0

Victor
Victor

Reputation: 31

First, condition choice != 'F' || 'f' is wrong. Correct condition is ((choice != 'F') && (choice != 'f')).

For work with lowercase you may use this condition in while loop:

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

or use toupper/tolower functions from ctype.h

Upvotes: 3

Related Questions