变量可能未初始化/未初始化使用

时间:2018-07-02 03:09:51

标签: c++ try-catch

我正在用C ++编写一个英制转换程序,并且试图使用try,throw,catch拒绝“ main”函数中的负/非数字值。

我的两个问题是:

1。) 每当我在控制台中输入“ g”时,都会得到一个输出:0英寸等于0厘米,然后得到我要弹出的错误显示。我只需要输出错误显示即可。

2。)当我输入一个负数(如-3)时,如果我想告诉我输入无效,我将得到正确的转换为负数。

这是我的代码。

#include <iostream>
#include <cctype>
char menuSelect();
using namespace std;

int main(int argc, const char * argv[])
{
    double inches;
    double centimeters;
    char select;
    try
    {
        do
        {

            if (centimeters < 0.0 || inches < 0.0)
                throw 0;
            if (!cin)
                throw 0;

            select = menuSelect();
            if (select == 'E')
            {
                cout << "Enter the number of inches: ";
                cin >> inches;
                centimeters = inches * 2.54;
                cout << inches << " inches is equal to " << centimeters
                        << " centimeters." << endl;
            }
            else if (select == 'M')
            {
                cout << "Enter the number of centimeters: ";
                cin >> centimeters;
                inches = centimeters / 2.54;
                cout << centimeters << " Centimeters is equal to " << inches
                        << " inches." << endl;
            }

        } while (select != 'Q');

    }
    catch (int errID)
    {
        cout << "Error: " << errID << endl;
        cout << "Please enter a positive number. ";
    }
    return 0;

}

1 个答案:

答案 0 :(得分:0)

应该是这样的:(我在输入之后加上了标记bool bNeg = falseif (inches>=0)if (centimeters>=0),并且如果输入的'E'或'M为负'设置bNeg = true

    bool bNeg = false;

    if (select == 'E')
    {
        cout << "Enter the number of inches: ";
        cin >> inches;
        if (inches>=0) { // No meaning to negative values
            centimeters = inches * 2.54;
            cout << inches << " inches is equal to " << centimeters
                << " centimeters." << endl;
        }
        else bNeg = true;

    }
    else if (select == 'M')
    {
        cout << "Enter the number of centimeters: ";
        cin >> centimeters;
        if (centimeters>=0) { // No meaning to negative values
            inches = centimeters / 2.54;
            cout << centimeters << " Centimeters is equal to " << inches
                << " inches." << endl;
        }
        else bNeg = true;
    }

    if (bNeg) {
        // tbd: say what you want to say
    }