while尝试捕获的循环在坏的cin输入时失败 [英] While loop with try catch fails at bad cin input

查看:115
本文介绍了while尝试捕获的循环在坏的cin输入时失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法弄清楚为什么在获得非int输入后陷入循环。我试过cin.flush(),它似乎不存在,cin.clear(),这似乎应该工作,甚至cin.sync()后阅读别人的文章,它的工作,但没有似乎很有意义。还尝试了cin.bad()。

I can't seem to figure out why this falls into a loop after getting non-int input. I've tried cin.flush(), which doesn't seem to exist, cin.clear(), which seems like it should work, even cin.sync() after reading someone else post about it working, but didn't seem to make much sense. Also tried cin.bad().

非常感谢您的帮助


请输入第一个数字:f
对不起,我不认为这是一个数字?

Please enter the first number: f Sorry, I don't think that's a number?

请输入第一个数字:对不起,
我不认为这是一个数字?

Please enter the first number: Sorry, I don't think that's a number?

请输入第一个数字:对不起,
我不认为这是一个数字?

Please enter the first number: Sorry, I don't think that's a number?

请输入第一个数字:对不起,
我不认为这是数字?

Please enter the first number: Sorry, I don't think that's a number?

请输入第一个数字:对不起,
我不认为这是一个数字?对不起,
你没有得到任何更多的尝试。按
任意键继续。 。 。

Please enter the first number: Sorry, I don't think that's a number?Sorry, you d on't get any more tries. Press any key to continue . . .



#include <iostream>
using namespace std;

int main(){
    int entry;
    int attempts = 1;
    int result;
    while(attempts <= 5) {
        try {
            cout << "\n\nPlease enter the first number: ";
            cin >> entry;
            if (cin.fail())
                throw "Sorry, I don't think that's a number?";
            if (entry < 0)
                throw "Sorry, no negative numbers. Try something else? ";
            cout << "\nNow the second number: ";
            cin >> entry;
            cin.clear();
            cin.get();
        }
        catch (char* error) {
            cout << error;
            attempts++;
        }
    }
    if (attempts > 5)
        cout << "Sorry, you don\'t get any more tries.\n";
    system("pause");
    return 0;
}


推荐答案

在这种情况下,如果用户给出无效输入,则要做。通常在这些情况下,最好的解决方案是从输入中读取一行并将其丢弃。

You should think carefully what you want to do if user gives invalid input in this case. Usually in these cases the best solution is to read one line from the input and throw it away.

尝试将 cin.clear code>和 std :: cin.ignore(std :: numeric_limits< streamsize> :: max(),'\\\
');
cin.clear()清除cin中的故障状态, cin.ignore()等待输入缓冲区。

Try putting cin.clear() and std::cin.ignore(std::numeric_limits<streamsize>::max(),'\n'); in your catch clause. cin.clear() clears the failure state in cin, and cin.ignore() throws away rest of the line waiting in the input buffer.

(是的,你可能应该重新考虑你的异常使用)。

(And yes, you probably should rethink your use of exceptions).

这篇关于while尝试捕获的循环在坏的cin输入时失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆