問題描述
我在上我的第二堂 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++的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!