简体   繁体   中英

Need help stopping loop

#include <iostream>
#include <iomanip>
#include <cstdlib>

using namespace std;

int main()

{
    int age = 0, age0_18 = 0, age19_30 = 0, age31_40 = 0, age41_60 = 0, age61_ = 0, numberofattendees = 0, sum = 0, snacks = 0, snack1_2 = 0, snack2_3 = 0, snack3_4 = 0, snack4_5 = 0,snack5_6 = 0, snack7_ = 0,numberofsnacks = 0;
    int total;
    int Total;


    cout <<"    " "==========================" << endl;
    cout <<"      " "THEATER STATS PROGRAM" << endl;
    cout <<"    " "==========================" << endl;
    cout << endl;
    cout << "Movie theater snacks available for purchase" << endl;
    cout << "==========================================" << endl;
    cout << "1 - Soft Drink (such as Coca Cola, ICCEE, Mineral Water etc...)" << endl;
    cout << "2 - Popcorn" << endl;
    cout << "3 - Nachos" << endl;
    cout << "4 - Soft drink & Popcorn" << endl;
    cout << "5 - Soft drink & Nachos" << endl;
    cout << "6 - Organic and Gluten-free snacks" << endl;
    cout << "7 - None" << endl;
    cout << "==========================================" << endl;
    cout << endl;

    while (age != -1)

            {
                numberofattendees++;
                numberofsnacks++;

                if (age >= 0)
                {
                    sum = sum + age;
                }
                if (age >= 0 && age <= 18)
                {
                    age0_18++;
                }
                if (age >= 19 && age <= 30)
                {
                    age19_30++;
                }
                if (age >= 31 && age <= 40)
                {
                    age31_40++;
                }
                if (age >= 41 && age <= 60)
                {
                    age41_60++;
                }
                if (age >= 61)
                {
                    age61_++;
                }
                if (snacks >= 0)
                {
                    sum = sum + Total;
                }
                if (snacks >= 1 && snacks <= 2)
                {
                    snack1_2++;
                }
                if (snacks >= 2 && snacks <= 3)
                {
                    snack2_3++;
                }
                if (snacks >= 3 && snacks <= 4)
                {
                    snack3_4++;
                }
                if (snacks >= 4 && snacks <=5)
                {
                    snack4_5++;
                }
                if (snacks >= 6 && snacks <=7)
                {
                    snack5_6++;
                }
                if (snacks >= 7)
                {
                        snack7_++;
                }
                cout << "Enter age of attendee (-1 to quit): ";
                cin >> age;
                cout << "Movie theater snack purchased (Select 1-7): ";
                cin >> snacks;
                while (snacks < 1 || snacks > 7)
                {
                    cout << "Invalid selection, please choose from 1 - 7" << endl;
                }
                cout << "---------------------------------------------" << endl;
                {}

            }
                cout << "Movie theater snack purchased (Select 1-7): ";
                cin >> snacks;
                cout << "---------------------------------------------" << endl;

                cout << endl;
                cout <<"==========================" << endl;
                cout <<"  " "THEATER STATS PROGRAM" << endl;
                cout <<"==========================" << endl;
                cout << endl;
                cout << "age 0 to 18: " << age0_18 << endl;
                cout << endl;
                cout << "age 19 to 30: " << age19_30 << endl;
                cout << endl;
                cout << "Age 31 to 40: " << age31_40 << endl;
                cout << endl;
                cout << "age 41 to 60: " << age41_60 <<endl;
                cout << endl;
                cout << "Over 60: " << age61_ << endl;
                cout << endl;

                total = sum / numberofattendees;

                cout << "The average age was " << total << endl;
                cout << endl;
                cout << "The youngest person in attendance was " << endl;
                cout << endl;
                cout << "The oldest person in attendance was " << endl;
                cout << endl;


            return 0;       
}

The program asks the user what the age of the attendee is at the movie theater is and also what snack they decide to get.

What i am trying to do is have the program show an error message when the user puts in a number that is not between 1-7 for the snack part. I have got it to show the message but i can not make it stop. (Meaning that it will show the message when something other than 1-7 is inputed but it is infinite.)

How/what am i doing wrong or what did i include that isn't correct?

Also, I am having trouble with inputting the age as well. I have -1 set up in the age part for when the user no longer wants to put in other attendees but it seems that whenever i put in -1, it continues to ask for the snack number and THEN quits.

cout << "Movie theater snack purchased (Select 1-7): ";
cin >> snacks;
while (snacks < 1 || snacks > 7)
{
    cout << "Invalid selection, please choose from 1 - 7" << endl;
}

The problem is your while loop never changes the value of snacks . So the condition to enter the loop is always valid, making it loop infinitely. It should instead be a one-time if check, and the question about what snack should be in a do/while loop so that you can ask again and get new values for snack . I'm choosing do/while because I need to ask at least once.

do {
    cout << "Movie theater snack purchased (Select 1-7): ";
    cin >> snacks;
    if (snacks < 1 || snacks > 7)
        cout << "Invalid selection, please choose from 1 - 7" << endl;
} while (snacks < 1 || snacks > 7);

There are probably ways to clean that up a little more (like a function that validates a snack selection, seems overkill here though).

As for the age thing, a quick look at your code shows that you don't check the age until you start your while loop again. So it makes sense that it asks you about a snack, the loop body is just continuing to execute. One change you could make is to set your outer loop to be infinite, and do an age check immediately after you acquire it.

while(1) {
    // ...
    cout << "Enter age of attendee (-1 to quit): ";
    cin >> age;
    if (age == -1)
        break;  // interrupts your loop and kicks you out immediately
    // ...
}

This also means that your big if chunks should be moved further down because you are checking against your variables before you've actually got values from the user.

I'm looting from sweenish's answer to demonstrate that this is a great place to use a function:

bool getSnacks(int & snacks)
{
    cout << "Movie theater snack purchased (Select 1-7): ";
    cin >> snacks;
    if (snacks < 1 || snacks > 7)
    {
        cout << "Invalid selection, please choose from 1 - 7" << endl;
        return false;
    }
    return true;
}

The while loop now becomes

while (!getSnacks(snacks))
{
    // does absolutely nothing!
}

or the more compact, but odd-looking

while (!getSnacks(snacks));

This allows you to get some of the logic out of the main function and into a simple function that is easy to understand and easy to test. Plus you can generalize this function a bit and possibly get some reuse out of it

bool getBoundedInt(int & val,
                   int min,
                   int max,
                   const std::string & prompt)
{
    cout << " Please select " << prompt << " (Select "<< min << "-" << max << "): ";
    cin >> val;
    if (val < min || val > max)
    {
        cout << "Invalid selection, please choose from << min << " - " << max << endl;
        return false;
    }
    return true;
}

And you can use this function to get all sorts of information, like

while (!getBoundedInt(snacks, 1, 7, "snack"));
while (!getBoundedInt(movie, 1, 9, "movie"));
while (!getBoundedInt(seat, 1, 42, "seat"));

The next step would be to move the loop into the function so that the function doesn't return until the user provides an acceptable value

int getBoundedInt(int min,
                   int max,
                   const std::string & prompt)
{

    cout << " Please select " << prompt << " (Select "<< min << "-" << max << "): ";
    int val;
    while (true)
    {
        cin >> val;
        if (val < min || val > max)
        {
            cout << "Invalid selection, please choose from << min << " - " << max << endl;
        }
        else
        {
            return val;
        }
    }
}

Now the usage is really simple:

snack = getBoundedInt(1, 7, "snack");
movie = getBoundedInt(1, 9, "movie");
seat = getBoundedInt(1, 42, "seat");

But what if the user enters something completely invalid like "Rubber Babybuggy bumpers"? You will also need some protection around cin >> val; to ensure the input could be parsed into an integer.

Your adventure in Input Validation (that's a search term you can research for more information and ideas) has only just begun.

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