如何使用菜单

时间:2015-05-10 04:53:18

标签: c++ loops if-statement menu while-loop

#include <iostream>
using namespace std;

int main()
{
    int food, product, total;
    double price;
    cout << "     Welcome To Maggie’s Shopping Cart Calculator!" << endl;
    char option; // user's entered option will be saved in this variable
    do{
    //Displaying Options for the menu
    cout << " 1) Please add an item to your cart " << endl;
    cout << " 2) Final Total Amount" << endl;
    cout << " 3) Quit the program" << endl;   //Prompting user to enter an option according to menu
    cout << " Please select an option : ";
    cin >> option;  // users option
    total = price;
    if (option == 1) // Checking if user selected option 1
    {
        cout << " Please enter item and the price : " << endl;
        cin >> food;
        cin >> price;
        cout << " Total amount so far: " << price << endl;
        }
        else if (option == 2)
            cout << "Total Amount so Far: " <<  total << endl;
        else if (option == 3) // Checking if user selected option 2
        {
            cout << " End Shopping Cart! " << endl;
        }
    }
        while (option != 3);
        system("pause");
        return 0;
    }
}

这是我的代码,我只是继续重复菜单,即使我选择了一个选项帮助!分配是有三个选项供用户选择,选择选择1后应重复菜单。我的代码不允许我输入任何信息。

2 个答案:

答案 0 :(得分:0)

您将选项变量定义为char,稍后将其作为int进行比较。尝试将其定义更改为int

答案 1 :(得分:0)

修改了你的代码,检查出来

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

int main()
{
int  product, total=0;int flag =1;string food;
double price;
cout << "     Welcome To Maggie’s Shopping Cart Calculator!" << endl;
int option; // user's entered option will be saved in this variable
do{
//Displaying Options for the menu
cout << " 1) Please add an item to your cart " << endl;
cout << " 2) Final Total Amount" << endl;
cout << " 3) Quit the program" << endl;   //Prompting user to enter an option              according to menu
cout << " Please select an option : ";
cin >> option;  // users option

if (option == 1) // Checking if user selected option 1
{
    cout << " Please enter item and the price : " << endl;
    cin >> food;
    cin >> price;total = total + price ;
    cout << " Total amount so far: " << total  << endl;
    }
    else if (option == 2)
        cout << "Total Amount so Far: " <<  total << endl;
    else if (option == 3) // Checking if user selected option 2
    {
        cout << " End Shopping Cart! " << endl;
        flag=0 ;

    }


  }
    while ( flag== 1);

    return 0;
}

希望这有用