简体   繁体   English

需要帮助停止循环

[英]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.我想要做的是让程序在用户输入一个不在 1-7 之间的数字作为零食部分时显示错误消息。 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.) (意思是当输入 1-7 以外的内容时它会显示消息,但它是无限的。)

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.我在年龄部分设置了-1,当用户不想再加入其他与会者时,但似乎每当我输入-1时,它都会继续询问零食编号然后退出。

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 .问题是您的 while 循环永远不会改变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 .相反,它应该是一次性的 if 检查,以及关于 do/while 循环中应该包含什么零食的问题,这样您就可以再次询问并获得snack的新值。 I'm choosing do/while because I need to ask at least once.我选择 do/while 是因为我需要至少询问一次。

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).可能有一些方法可以进一步清理它(比如验证零食选择的 function,不过在这里似乎有点矫枉过正)。

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.至于年龄问题,快速查看您的代码表明您在再次启动 while 循环之前不会检查年龄。 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.这也意味着您的大 if 块应该进一步向下移动,因为您在实际从用户那里获得值之前检查您的变量。

I'm looting from sweenish's answer to demonstrate that this is a great place to use a function:我从 sweenish 的回答中掠夺来证明这是使用 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 循环现在变成

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.这使您可以从main的 function 中获取一些逻辑,并将其转换为易于理解和易于测试的简单 function。 Plus you can generalize this function a bit and possibly get some reuse out of it另外,您可以稍微概括一下这个 function 并可能从中得到一些重用

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您可以使用此 function 获取各种信息,例如

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下一步是将循环移动到 function 中,以便 function 在用户提供可接受的值之前不会返回

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"?但是,如果用户输入一些完全无效的内容,例如“Rubber Babybuggy 保险杠”,该怎么办? You will also need some protection around cin >> val;您还需要在cin >> val; to ensure the input could be parsed into an integer.以确保可以将输入解析为 integer。

Your adventure in Input Validation (that's a search term you can research for more information and ideas) has only just begun.您在输入验证(这是一个您可以研究以获取更多信息和想法的搜索词)的冒险才刚刚开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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