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

Good input validation loop using cin - C++(使用 cin 的良好输入验证循环 - C++)
本文介绍了使用 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, '
');
    }
}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(), '
');
    }
}

除了只跳过 80 个字符之外,这些只是小问题,更多的是喜欢的风格.

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to enable C++11 in Qt Creator?(如何在 Qt Creator 中启用 C++11?)
How to convert QString to std::string?(如何将 QString 转换为 std::string?)
Qt: can#39;t find -lGL error(Qt:找不到 -lGL 错误)
Serialization with Qt(使用 Qt 进行序列化)
Non-blocking worker - interrupt file copy(非阻塞工作者 - 中断文件复制)
How to link opencv in QtCreator and use Qt library(如何在 QtCreator 中链接 opencv 并使用 Qt 库)