switch语句直接进入默认值

时间:2014-11-08 02:53:02

标签: c++ switch-statement

在此开关中,无论用户输入什么,它总是会跳过所有情况并始终显示默认情况!!

        cout << "Enter an operator(+, -, *, /)" << endl;
        cin >> oper;
        cout << "Enter second number" << endl;
        cin >> second;
        if (second > 9999)
        {
            cout << "ERROR\n";
            system("PAUSE");
            continue;
        }
        switch (oper)
        {
            case '+':
                ans = add(first, second);
            case '-':
                ans = subtract(first, second);
            case '*':
                ans = multiply(first, second);
            case '/':
                ans = divide(first, second);
            default:
                cout << "ERROR\n";
                system("PAUSE");
                continue;
        }

2 个答案:

答案 0 :(得分:4)

实际上,它没有跳过这些情况,它进入它们然后执行进入下一个案例,最终以默认情况结束。您需要添加break语句才能突破switch

    switch (oper)
    {
        case '+':
            ans = add(first, second);
            break;
        case '-':
            ans = subtract(first, second);
            break;
        case '*':
            ans = multiply(first, second);
            break;
        case '/':
            ans = divide(first, second);
            break;
        default:
            cout << "ERROR\n";
            system("PAUSE");
            continue;
    }

答案 1 :(得分:0)

首先,您需要有break语句。如果您不包含这些,开关盒将不知道在哪里停止!

你可以修改这样的代码:

    cout << "Enter an operator(+, -, *, /)" << endl;
    cin >> oper;
    cout << "Enter second number" << endl;
    cin >> second;
    if (second > 9999)
    {
        cout << "ERROR\n";
        system("PAUSE");
        continue;
    }
    switch (oper)
    {
        case '+':
            ans = add(first, second);
        break;
        case '-':
            ans = subtract(first, second);
        break;
        case '*':
            ans = multiply(first, second);
        break;
        case '/':
            ans = divide(first, second);
        break;
        default:
            cout << "ERROR\n";
            system("PAUSE");
            continue;
    }