使用cin的良好输入验证循环-C ++ [英] Good input validation loop using cin - C++

查看:76
本文介绍了使用cin的良好输入验证循环-C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在第二个OOP课上,而我的第一堂课是用C#讲授的,所以我是C ++的新手,目前我正在练习使用cin进行输入验证.所以这是我的问题:

I'm in my second OOP class, and my first class was taught in C#, so I'm new to C++ and currently I am practicing input validation using cin. So here's my question:

这个循环是否构成了一种验证输入的好方法?还是有更普遍/可接受的方式做到这一点?

Is this loop I constructed a pretty good way of validating input? Or is there a more common/accepted way of doing it?

谢谢!

代码:

int taxableIncome;
int error;

// input validation loop
do
{
    error = 0;
    cout << "Please enter in your taxable income: ";
    cin >> taxableIncome;
    if (cin.fail())
    {
        cout << "Please enter a valid integer" << endl;
        error = 1;
        cin.clear();
        cin.ignore(80, '\n');
    }
}while(error == 1);

推荐答案

我不是为iostream开启异常的忠实粉丝. I/O错误还不够特殊,因为错误很可能经常发生.我只希望对不太常见的错误情况使用异常.

I'm not a huge fan of turning on exceptions for iostreams. I/O errors aren't exceptional enough, in that errors are often very likely. I prefer only to use exceptions for less frequent error conditions.

代码还不错,但是跳过80个字符有点武断,如果您弄乱了循环,则不需要错误变量(如果保留它,则应为bool).您可以将从cin读取的内容直接放入if中,这也许更像是Perl惯用语.

The code isn't bad, but skipping 80 characters is a bit arbitrary, and the error variable isn't necessary if you fiddle with the loop (and should be bool if you keep it). You can put the read from cin directly into an if, which is perhaps more of a Perl idiom.

这是我的看法:

int taxableIncome;

for (;;) {
    cout << "Please enter in your taxable income: ";
    if (cin >> taxableIncome) {
        break;
    } else {
        cout << "Please enter a valid integer" << endl;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
}

除了只跳过80个字符外,这些都是小问题,更多的是首选样式.

Apart from only skipping 80 characters, these are only minor quibbles, and are more a matter of preferred style.

这篇关于使用cin的良好输入验证循环-C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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