jeudi 22 avril 2021

How to use a loop with user input? [duplicate]

I am currently using a while loop that is true with an if statement that breaks the loop in the user inputs 'N' or 'n'. However I also need to make the loop repeat only if the user enters 'Y' or 'y'. If they press any other letter or number it should say "invalid answer. Try again." I've thought of using a while loop with cin.fail but it was not working. This is one case in a switch statement for a menu.

case 1:
        while (true) {
            char answer;
            ifstream menu("menu.txt");
            int num = 1;
            while (!menu.eof()) {
                string menuitem;
                getline(menu, menuitem);
                cout << num << ") ";
                cout << menuitem << endl;
                num++;
            }
            menu.close();
            cout << endl;
            cout << "What day is it? " << endl;
            cout << endl;
            cout << "A) Monday " << endl;
            cout << "B) Tuesday " << endl;
            cout << "C) Wednesday " << endl;
            cout << "D) Thursday " << endl;
            cout << "E) Friday " << endl;
            cout << "F) Saturday " << endl;
            cout << "G) Sunday " << endl;

            char days;
            cout << "Please enter a selection (A-G): ";
            cin >> days;

            if (days == 'A' || days == 'a')
                cout << "Monday's Special: chicken fingers and fries - $4.99 " << endl;
            else if (days == 'B' || days == 'b')
                cout << "Tuesday's Special: Cheeseburger and fries -  $6.99 " << endl;
            else if (days == 'C' || days == 'c')
                cout << "Wednesday's Special: $1.00 off a spicy or regular chicken with fries " << 
endl;
            else if (days == 'D' || days == 'd')
                cout << "Thursday's Special: 2 orders of boneless wings and fries - $4.99 " << endl;
            else if (days == 'E' || days == 'e')
                cout << "Friday's Special: soup and salad - $2.99 " << endl;
            else if (days == 'F' || days == 'f')
                cout << "Saturday's Special: chicken sandwich and fries - $5.99 " << endl;
            else if (days == 'G' || days == 'g')
                cout << "Sunday's Specal: chicken salad sandwich and chips - $3.99 " << endl;
            else {
                cout << "You didn't select a valid choice! " << endl;
            }
            cout << endl;
            cout << " Do you want to repeat the menu again? " << endl;
            cin >> answer;
            if (answer == 'N' || answer == 'n') {
                break;
            }
            
            }

Aucun commentaire:

Enregistrer un commentaire