在stackoverflow的好撒玛利亚人的帮助下,当来自用户的输入不是整数时,我已经到了以下代码来捕获异常:
signed int num;
while(true)
{
cin >> num;
try{
if(cin.fail()){
throw "error";
}
if(num>0){
cout<<"number greater than 0"<<endl;
}
}
catch( char* error){
cout<<error<<endl;
break;
}
}
现在假设程序被调用:checkint。如果我通过重定向文本文件中的输入来调用程序,请输入:input.txt,其中包含以下内容: 12 5 12 0 3 2 0
checkint <input.txt
输出: 我得到以下输出:
number greater than 0
number greater than 0
number greater than 0
number greater than 0
number greater than 0
error
为什么当文件中的所有输入都是整数时,它最终会抛出错误? 感谢
答案 0 :(得分:5)
.good()
,.bad()
,.eof()
和.fail()
:http://www.cplusplus.com/reference/iostream/ios_base/iostate/
flag value indicates
eofbit End-Of-File reached while performing an extracting operation on an input stream.
failbit The last input operation failed because of an error related to the internal logic of the operation itself.
badbit Error due to the failure of an input/output operation on the stream buffer.
goodbit No error. Represents the absence of all the above (the value zero).
试试这个:
while(cin >> num)
{
if(num>0){
cout<<"number greater than 0"<<endl;
}
}
// to reset the stream state on parse errors:
if (!cin.bad())
cin.clear(); // if we stopped due to parsing errors, not bad stream state
如果您希望获得例外,请尝试
cin.exceptions(istream::failbit | istream::badbit);
松散的笔记:
#include <stdexcept>
struct InputException : virtual std::exception
{
protected: InputException() {}
};
struct IntegerInputException : InputException
{
char const* what() const throw() { return "IntegerInputException"; }
};
// ...
throw IntegerInputException();
//
try
{
} catch(const InputException& e)
{
std::cerr << "Input error: " << e.what() << std::endl;
}
答案 1 :(得分:0)
我会说这是因为即使你已经阅读了最后的整数,你总是会回到cin >> num
语句。
如果你改变:
if (num > 0) {
cout << "number greater than 0" << endl;
}
成:
if (num > 0) {
cout << "number greater than 0\n";
} else {
cout << "number less than or equal to 0\n";
}
毫无疑问,你会看到七行输出然后抛出错误。
答案 2 :(得分:0)
因为它达到了EOF?输入中有5个正整数,0(无输出),然后达到EOF。