如何使用cin.fail()编写函数以确保main中的有效输入? [英] how to write a function using cin.fail() to ensure valid input in main?

查看:56
本文介绍了如何使用cin.fail()编写函数以确保main中的有效输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

部分要求是该函数不应带有任何参数.但是问题是我可以在哪里存储cin输入?我在这里遇到了无限循环.

Part of the requirement is that the function should not take any arguments. But the problem is that where can I store the cin input? I got an infinite loop here.

double getValidDouble(){
    string invalid_input;
    while (cin.fail()){
        cout << "You entered a value of the wrong type!" << endl;
        getline(cin,invalid_input);
        cout << "Enter a double this time: " << endl;  
    }
}

推荐答案

也许我并不完全关注,但是为什么不声明局部变量并返回它呢?

Maybe I'm not totally following but why not just declare a local variable and return it?

double getValidDouble(){
    string invalid_input;
    double val;
    cin >> val;
    while (cin.fail()){
        cout << "You entered a value of the wrong type!" << endl;
        cin.clear();
        getline(cin,invalid_input);
        cout << "Enter a double this time: " << endl;  
        cin >> val;
    }
    return val;
}

无限循环可能是由于您在错误发生后未执行 cin.clear()而引起的.

Infinite loop is probably due to you not doing cin.clear() after the error.

这篇关于如何使用cin.fail()编写函数以确保main中的有效输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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