简体   繁体   中英

I'm trying to make a menu in c++ and I don't understand why it doesn't loop

This is what I've tried so far. It might be that I'm using the worng do while syntax but I'm really stumped because I'm pretty sure I used this exact template to create a menu before. I think the condition in the while loop is wrong for some reason it ignores that line and stops the program.

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    char selection{};
    do{
        cout << "P: Print the numbers in the vector" << endl;
        cout << "A: Add a number to the vector" << endl;
        cout << "M: Display the mean of the vector" << endl;
        cout << "S: Display the smallest number in the vector" << endl;
        cout << "L: Display the largest number in the vector" << endl;
        cout << "Q: Quit" << endl;
        cout << "Enter your selection: ";
        cin >> selection;

        if (selection == 'P' || selection == 'p'){
            cout << "You chose to print" << endl;
        }
        else if (selection == 'A' || selection == 'a'){
            cout << "You chose to add a number to the vector" << endl;
        }
        else if (selection == 'M' || selection == 'm'){
            cout << "You chose to calculate the mean" << endl;
        }
        else if (selection == 'S' || selection == 's'){
            cout << "You chose to display the smallest number" << endl;
        }
        else if (selection == 'L' || selection == 'l'){
            cout << "You chose to display the largest number" << endl;
        } 
        else if (selection == 'Q' || selection == 'q'){
            cout << "Thank you for using the program" << endl;
        }
        else {
            cout << "Invalid selection try again" << endl;

        }
    }
    while (selection == 'Q' && selection == 'q');

    return 0;
}

as @Yksisarvinen wrote you have a problem in your condition, your current condition says that: if selection equal to Q and equal to q run the loop and I'm guessing that you don't want what so you need to change the loop condition from this -

  while (selection == 'Q' && selection == 'q');

to this -

 while (selection != 'Q' && selection != 'q');

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM