[英]C++ cin Input Validation in a While Loop
除了一個小問題外,我的代碼大部分都在工作。 雖然它應該只接受整數,但它也接受以整數開頭的用戶輸入,例如6abc
。 我在這里看到了一個解決方法,但是它將輸入類型更改為字符串並添加了更多代碼行。 我想知道是否有更簡單的方法來解決這個問題:
int ID;
cout << "Student ID: ";
// error check for integer IDs
while( !( cin >> ID )) {
cout << "Must input an integer ID." << endl ;
cin.clear() ;
cin.ignore( 123, '\n' ) ;
}
一句話——不。
但是您可以做的是先將整個單詞讀入std::string
,然后將整個單詞轉換為int
,檢查該轉換中的錯誤,例如:
int ID;
string input;
do
{
cout << "Student ID: ";
if (!(cin >> input))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
else
{
size_t pos = 0;
try
{
ID = stoi(input, &pos);
if (pos == input.size())
break;
}
catch (const std::exception &) {}
}
cout << "Must input an integer ID." << endl;
}
while (true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.