我目前是一名工程本科学生,对编程有很强的兴趣和热情。这些天,我试图通过一些在线参考和教程网站来学习C++。但还是有一些问题我自己想不出来。
谁能帮我解释一下cin.exceptions(ios_base::failbit); //throw exception on failbit set的字面意思吗?
我知道ios_base::failbit和异常(exception是STL中的一个类)。
根据我的理解,这意味着当输入不是一个数字时,它将导致failbit标志,一旦发生这种情况,系统将抛出一个异常。
我不明白为什么在括号中是exception而不是exceptions。
//this is a piece of code on my lecture notes
#include <iostream>
#include <string>
using namespace std;
int read_int(const string& prompt);
int main()
{
int n;
n=read_int("Enter a number: ");
cout<<"n: "<<n<<endl;
}
int read_int(const string& prompt){
cin.exceptions(ios_base::failbit);//Why this line "exceptions" different from the next "exception"
int num=0;
while(true){
try{
cout<<prompt;
cin>>num;
return num;
}catch(exception ex)// what does "exception" here mean?
{
cout<<"Bad numeric string--try again\n";
cin.clear();
cin.ignore();
}
}
}发布于 2015-12-19 04:00:02
在cin.exceptions(...)中,异常是一个函数名。具体来说,这一功能让我们为流设置一个新的异常掩码。
在catch(exception ex)中,异常是类型名称。特别是exception类型,它是异常的基本类型。在本例中,这意味着您将捕获任何异常,因为它们都应该从exception继承。
https://stackoverflow.com/questions/34367065
复制相似问题