Как исправить мой код от слишком раннего завершения?

#c #visual-c

#c #visual-c

Вопрос:

Каждый раз, когда я запускаю код и намеренно ввожу неправильный ввод, чтобы получить результат Please enter a valid choice! , и он делает это, но затем программа просто завершается.

Это программа на C , которая имитирует торговый автомат. Я использую Visual Studios. Я попытался использовать цикл while вне коммутатора, используя цикл for, использовал оператор if и другие вещи, в которых я не совсем уверен (использовал то, что я нашел в Google).

 #include "pch.h"
#include <iostream>
#include <string>
#include <cctype>
#include <iomanip>
using namespace std;

struct Drinks
{
    string name;
double cost;
int number;
};


class Simulation
{
private:
    Drinks softDrink[5];
    double money;
bool enoughMoney;
int amount;
double total;
void dailyReport();
void inputMoney(int);

public:
Simulation();
void displayChoices();
void buyDrink(int);
~Simulation();


};

Simulation::Simulation()
{
for (int x = 0; x < 5; x  )
{
    if (x == 4)
    {
        softDrink[x].cost = 1.50;
    }
    else
    {
        softDrink[x].cost = 1.00;
    }

    softDrink[x].number = 20;
}

softDrink[0].name = "Cola";
softDrink[1].name = "Root-beer";
softDrink[2].name = "Orange soda";
softDrink[3].name = "Grape soda";
softDrink[4].name = "Bottled water";

money = 0.0;
amount = 0;
total = 0.0;
}
void Simulation::displayChoices()
{
cout << fixed << setprecision(2);
for (int x = 0; x < 5; x  )
{
    cout << x   1 << "." << softDrink[x].name << " : $" << softDrink[x].cost << endl;
}
}
void Simulation::inputMoney(int choice)
{
cout << "The cost for " << softDrink[choice - 1].name << " is $" << softDrink[choice - 1].cost << endl;
cout << "How much money will you insert? ";
cin >> money;

if (money < softDrink[choice - 1].cost)
{
    cout << "Can not deliver beverage, not enough money" << endl;
    enoughMoney = false;
}
else
{
    enoughMoney = true;
}
}
void Simulation::buyDrink(int choice)
{
char purchaseChoice;

inputMoney(choice);

if (enoughMoney)
{

    cout << "Do you want to make a purchase for this drink?(Y/N) ";
    cin >> purchaseChoice;
    while (purchaseChoice != 'Y' amp;amp; purchaseChoice != 'N')
    {
        cout << "Please enter correct input, purchase drink (Y/N)? ";
        cin >> purchaseChoice;
    }


    if (purchaseChoice == 'Y')
    {
        if (softDrink[choice - 1].number <= 0)
        {
            cout << "We are sold out" << endl;
            cout << "Here is your money back $" << money << endl;
        }
        else
        {
            cout << "Here is your beverage" << endl;
            total  = softDrink[choice - 1].cost;
            softDrink[choice - 1].number -= 1;
        }


        if (money > softDrink[choice - 1].cost)
        {
            money -= softDrink[choice - 1].cost;
            cout << "Here is your change $" << money << endl;
        }
    }
    else
    {
        cout << "Here is your money back $" << money << endl;
    }
}
}
Simulation::~Simulation()
{
for (int x = 0; x < 5; x  )
{
    cout << "There are " << softDrink[x].number << " " << softDrink[x].name << " left in the machine" << endl;
}

cout << "The total amount of money collected during the day is $" << total << endl;
}



int main()
{
int choice;
string line;
Simulation machine;

cout << fixed << setprecision(2);


do
{
    cout << endl << "Drink Machine Menu" << endl;
    machine.displayChoices();
    cin >> choice;

    switch (choice)
    {
        case 1: machine.buyDrink(choice);
            break;

        case 2: machine.buyDrink(choice);
            break;

        case 3: machine.buyDrink(choice);
            break;

        case 4: machine.buyDrink(choice);
            break;

        case 5: machine.buyDrink(choice);
            break;
        default: cout << endl << "Please enter a valid choice!" << endl << endl;
            cin >> choice;
    }
} while (choice != 6 amp;amp; choice >= 1 amp;amp; choice <= 5);
return 0;
}
  

Я ожидал, что он будет продолжать сообщать пользователю, Please enter a valid choice! но он выводит только один раз, а затем завершает программу

Комментарии:

1. (choice != 6 amp;amp; choice >= 1 amp;amp; choice <= 5) Если вы не ввели число от 1 до 5, оно выйдет из вашего цикла.

2. @drescherjm как мне это исправить? Должен ли я использовать || вместо этого?

Ответ №1:

вы можете изменить условие while на

 while (choice != 6);
  

и он не выйдет из цикла, если вы не введете 6 (на случай, если вы захотите выйти при вводе).
Остальное обрабатывается в коммутаторе, и вам не нужно снова проверять его в while.