Ale*_*lex 17 c++ validation loops
我是第二个OOP课程,我的第一堂课是用C#教的,所以我是C++的新手,目前我正在使用cin练习输入验证.所以这是我的问题:
这个循环我构建了一个很好的验证输入的方法吗?或者有更常见/可接受的方式吗?
谢谢!
码:
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);
Run Code Online (Sandbox Code Playgroud)
P-N*_*uts 30
我不是开启iostreams异常的忠实粉丝.I/O错误不够特别,因为错误通常很可能.我更喜欢使用异常来减少错误条件.
代码也不错,但跳过80个字符有点武断,如果你摆弄循环就不需要错误变量(bool如果你保留它就应该这样).你可以将读取cin直接放入一个if,这可能更像是一个Perl习语.
这是我的看法:
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');
}
}
Run Code Online (Sandbox Code Playgroud)
除了仅跳过80个字符外,这些只是轻微的狡辩,更多的是首选风格.
小智 5
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;
}
Run Code Online (Sandbox Code Playgroud)
所以你看到我使用字符串输入,然后将其转换为整数.这样,有人可以键入enter,'mickey mouse'或者其他任何东西,它仍会响应.
#include <string>和<sstream>