[英]How to catch this exception C++
我想捕獲有人在cin上未提供數字值時發生的異常,因此程序將讀取下一個值。
#include <iostream>
using namespace std;
int main()
{
int x = 0;
while(true){
cin >> x;
cout << "x = " << x << endl;
}
return 0;
}
毫無例外。 相反, cin
設置了一個“輸入錯誤”標志。 您想要的是:
while ((std::cout << "Enter input: ") && !(std::cin >> x)) {
std::cin.clear(); //clear the flag
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n'); //discard the bad input
std::cout << "Invalid input; please re-enter.\n";
}
這一系列問題很好地說明了這一點。
如果您確實想使用異常處理,則可以執行以下操作:
cin.exceptions(ios_base::failbit); // throw on rejected input
try {
// some code
int choice;
cin >> choice;
// some more code
} catch(const ios_base::failure& e) {
cout << "What was that?\n";
break;
}
添加類似:
if(cin.fail())
{
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),' ');
cout << "Please enter valid input";
}
int main()
{
int x = 0;
cin.exceptions(ios::failbit);
while(true){
try
{
cin>>x;
}
catch(ios_base::failure& e)
{
//..
}
cout<<"x = "<<x<<endl;
}
return 0;
}
這應該工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.