【问题标题】:C++ Checking for an integer.C++ 检查整数。
【发布时间】:2013-09-02 07:10:54
【问题描述】:

C++ 新手。在处理错误时出现正确循环的问题。我正在尝试检查用户输入是否为整数,并且为正数。

do{
    cout << "Please enter an integer.";
    cin >> n;

    if (cin.good())
    {
        if (n < 0) {cout << "Negative.";}
        else {cout << "Positive.";}
    }
    else
    {
        cout << "Not an integer.";
        cin.clear();
        cin.ignore();
    }
}while (!cin.good() || n < 0);

cout << "\ndone.";

当输入一个非整数时,循环中断。我觉得我误解了cin.clear()cin.ignore() 的固有用法以及cin 在此循环中的状态。如果我删除cin.ignore(),循环将变为无限。为什么是这样?我该怎么做才能使它成为一个运行优雅的循环?谢谢。

【问题讨论】:

    标签: c++ cin


    【解决方案1】:

    在您的非整数分支中,您正在进一步调用 cin 方法,因此 cin.good() 被重置为 true。

    你可以把你的代码改成这样:

    while(1) { // <<< loop "forever"
        cout << "Please enter an integer.";
        cin >> n;
    
        if (cin.good())
        {
            if (n < 0) {cout << "Negative.";}
            else { cout << "Positive."; break; }
        }                            // ^^^^^ break out of loop only if valid +ve integer
        else
        {
            cout << "Not an integer.";
            cin.clear();
            cin.ignore(INT_MAX, '\n'); // NB: preferred method for flushing cin
        }
    }
    
    cout << "\ndone.";
    

    或者您可以像这样进一步简化它:

    while (!(cin >> n) || n < 0) // <<< note use of "short circuit" logical operation here
    {
        cout << "Bad input - try again: ";
        cin.clear();
        cin.ignore(INT_MAX, '\n'); // NB: preferred method for flushing cin
    }
    
    cout << "\ndone.";
    

    【讨论】:

    • 这非常有效,谢谢!我什至不认为我选择的循环阻碍了我。感谢您的帮助和解释。
    • 一旦用户输入垃圾(即“abc”之类的东西),第二个版本会不会导致无限循环?您需要在循环之前提取(或忽略)垃圾(但在 clear() 之后)。
    • @James:很好 - 谢谢 - 我现在已经修复了它(并且实际测试了它!)。
    【解决方案2】:
    int n;
    
    while (!(cin >> n)||n<0)//as long as the number entered is not an int or negative, keep checking
    {
    cout << "Wrong input. Please, try again: ";
    cin.clear();//clear input buffer
    
    }
    //only gets executed when you've broken out of the while loop, so n must be an int
    cout << "Positive.";
    
    cout << "\ndone.";//finished!
    

    应该做你想做的。

    【讨论】:

    • 现在我检查了它,它甚至没有按照他的要求做。如果输入是好的你应该离开只有当它是负面的......
    • @NoIdeaForName 抱歉,没发现。谢谢你的收获:)
    • 如果输入一个非整数,这个循环会变成无限的。和我的循环完全一样。
    • 输入整数后总是中断。只有输入负整数时,原始代码才会中断。
    • 我相信只有在输入 整数 (>= 0) 时才会中断。
    猜你喜欢
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 2020-06-21
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多