在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

当文件中的所有输入均为整数时,为什么最后会引发错误?
谢谢

最佳答案

您也正在检测eof。阅读.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

如果您希望获得异常(exception),请尝试
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;
     }
    

    07-28 07:37