简体   繁体   English

使用 cin 的良好输入验证循环 - C++

[英]Good input validation loop using cin - C++

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.我在上我的第二堂 OOP 课,我的第一堂课是用 C# 教授的,所以我是 C++ 的新手,目前我正在使用 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?或者有更常见/接受的方式吗?

Thanks!谢谢!

Code:代码:

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);

I'm not a huge fan of turning on exceptions for iostreams.我不太喜欢为 iostreams 打开异常。 I/O errors aren't exceptional enough, in that errors are often very likely. I/O 错误还不够特殊,因为错误通常很可能发生。 I prefer only to use exceptions for less frequent error conditions.我更喜欢只在不太频繁的错误情况下使用异常。

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).代码还不错,但是跳过 80 个字符有点随意,如果您摆弄循环,则不需要错误变量(如果保留它应该是bool )。 You can put the read from cin directly into an if , which is perhaps more of a Perl idiom.您可以将cin的读取内容直接放入if ,这可能更像是 Perl 习语。

Here's my take:这是我的看法:

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');
    }
}

Apart from only skipping 80 characters, these are only minor quibbles, and are more a matter of preferred style.除了只跳过 80 个字符外,这些只是小问题,更多的是首选风格。

int taxableIncome;
string strInput = "";
cout << "Please enter in your taxable income:\n";

while (true) 
{
    getline(cin, strInput);

    // This code converts from string to number safely.
    stringstream myStream(strInput);
    if ( (myStream >> taxableIncome) )
        break;
    cout << "Invalid input, please try again" << endl;
}

So you see I use string for input and then convert that to an integer.所以你看到我使用字符串作为输入,然后将其转换为整数。 This way, someone could type enter, 'mickey mouse' or whatever and it will still respond.这样,有人可以输入回车、“米老鼠”或其他任何东西,它仍然会响应。
Also #include <string> and <sstream>还有 #include <string><sstream>

Might you not consider try/catch, just to get you used to the concept of exception handling?你可能不考虑 try/catch,只是为了让你习惯异常处理的概念?

If not, why not use a boolean, instead of 0 and 1?如果不是,为什么不使用布尔值,而不是 0 和 1? Get into the habit of using variables of the correct type (and of creating types where needed)养成使用正确类型变量的习惯(并在需要时创建类型)

Cin.fail() is also discussed at http://www.cplusplus.com/forum/beginner/2957/ http://www.cplusplus.com/forum/beginner/2957/也讨论了 Cin.fail()

In fact, in many places ...其实很多地方...

http://www.google.com.sg/#hl=en&source=hp&q=c%2B%2B+tutorial&btnG=Google+Search&meta=&aq=f&oq=c%2B%2B+tutorial http://www.google.com.sg/#hl=en&source=hp&q=c%2B%2B+tutorial&btnG=Google+Search&meta=&aq=f&oq=c%2B%2B+tutorial

you might study some of those and try to follow the explanations of why things should be done a certain way.您可能会研究其中的一些,并尝试遵循为什么应该以某种方式完成工作的解释。

But, sooner or later, you ought to understand exceptions...但是,迟早你应该了解异常...

One minor quibble is that the error helper variable is completely redundant and is not needed:一个小问题是错误辅助变量是完全多余的,不需要:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM