【问题标题】:How to check the user input in c++如何在 C++ 中检查用户输入
【发布时间】:2019-09-29 18:24:27
【问题描述】:

在下面的代码中,我试图在“SOMECLASS”类的public空间中创建一个函数,该函数将接受由浮点值组成的用户输入(在private 同一类的空间)并验证用户输入。如果输入的值不是浮点数,则会显示错误消息,并且用户将有机会重新输入该值。但是,一旦输入了一些垃圾,循环就会从头开始运行,使用户再次输入所有这些值。

P.S:我知道可以创建多个循环来分别检查每个值并在语句正确时中断循环,但我想知道是否有更简单的方法。

提前感谢您的帮助。

void SOMECLASS::USER_INPUT() {
    bool loopBool = true; // it is used to manage the do/while loop below;

    do { // the loop is going to run for as long as the boolean is true;

        cout << "   Enter the frequency of the cumputer's CPU in GHz: ";
        cin >> float1;

        if (!float1) { // checks if the value entered is valid;
            cin.clear();
            cin.ignore (numeric_limits<streamsize>::max(), '\n');
            cout << "INVALID INPUT!!!" << endl << endl;
        }

        else {
            cout << "   Enter the Hard Drive Capacity in TB: ";
            cin >> float2;

            if (!float2) { // checks if the value entered is valid;
                cin.clear();
                cin.ignore(numeric_limits<streamsize>::max(), '\n');
                cout << "INVALID INPUT" << endl << endl;
            }

            else {
                cout << "   Enter the capacity of your RAM in GB: ";
                cin >> float3;

                if (!float3) { // checks if the value entered is valid;
                    cin.clear();
                    cin.ignore(numeric_limits<streamsize>::max(), '\n');
                    cout << "INVALID INPUT" << endl << endl;
                }
                loopBool = false;
            }
        }
    } while (loopBool);
};

输出:

Computer #1/2
 |--> Enter the frequency of the cumputer's CPU in GHz: 2.3
 |--> Enter the Hard Drive Capacity in TB: 4
 |--> Enter the capacity of your RAM in GB: asd
INVALID INPUT

 `--> The final cost is: ...

期望的输出:

Computer #1/2
 |--> Enter the frequency of the cumputer's CPU in GHz: 2.3
 |--> Enter the Hard Drive Capacity in TB: 4
 |--> Enter the capacity of your RAM in GB: asd
 INVALID INPUT
 |--> Enter the capacity of your RAM in GB: 16
 `--> The final cost is: ...

【问题讨论】:

  • 使用if (!float1),您如何识别来自有效0.0 的失败输入?您需要检查 stream 的状态。

标签: c++ visual-c++ input


【解决方案1】:

如果数字必须是浮点数(小数),那么您可以这样做:- 天花板(数字)楼层(数字)

如果是整数值,则 floor 和 ceil 将相等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 2014-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多