切换焦炭机代码的声明

时间:2014-10-11 04:44:21

标签: c++ switch-statement

我总是在if语句中使用else switch语句,但我决定尝试切换。我用一个开关做了基本的可乐机程序,我不能为我的生活弄清楚为什么它不起作用应该如何。当我使用数字1-5作为我的输入时,它继续给出开关默认错误消息而不是case cout语句(例如"你选择了Coke")。显然,我没有看到/

一些错误
#include <iostream>

using namespace std;

int main()
{
    int number;

    cout << "Beverage List" << endl;
    cout << "Coke = 1" << endl;
    cout << "Dr. Pepper = 2" << endl;
    cout << "Water = 3" << endl;
    cout << "Sprite = 4" << endl;
    cout << "Lemonade = 5" << endl << endl << endl;
    cout << "Enter a number to choose a beverage: ";
    cin >> number;

    switch (number)
    {
    case '1':
        cout << "You chose Coke";
        break;

    case '2':
        cout << "You chose Dr. Pepper";
        break;

    case '3':
        cout << "You chose Water";
        break;

    case '4':
        cout << "You chose Sprite";
        break;

    case '5':
        cout << "You chose Lemonade";
        break;

    default:
        cout << "Error: Choice was not valid. Here is your money back.";

    }

    cout << "\n";
    system("pause");
    return 0;
}

2 个答案:

答案 0 :(得分:2)

字符'1'与数字1不同。

更改

case '1':

case 1:

答案 1 :(得分:2)

看起来你的case语句是比较字符,而不是整数:

case '5':

请改为尝试:

case 5: