问题
With the help from good samaritans from stackoverflow, I have come till the following code to catch exceptions when the input from user is not an integer:
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;
}
}
Now assume the program is called: checkint. If I call the program by redirecting the input from a text file, say: input.txt, which has the following contents: 12 5 12 0 3 2 0
checkint <input.txt
Output: I get the following output:
number greater than 0
number greater than 0
number greater than 0
number greater than 0
number greater than 0
error
Why is it throwing the error in the end, when all the input in the file are integers? Thanks
回答1:
you are detecting eof too. Read up on .good()
, .bad()
, .eof()
and .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).
Try this:
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
If you prefer getting the exception, try
cin.exceptions(istream::failbit | istream::badbit);
Loose notes:
- using streams in exception mode is not common practice
- throwing primitive types is not common practice. Consider writing
.
#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;
}
回答2:
I would say it's because you always return to the cin >> num
statement even after you have read the final integer.
If you change:
if (num > 0) {
cout << "number greater than 0" << endl;
}
into:
if (num > 0) {
cout << "number greater than 0\n";
} else {
cout << "number less than or equal to 0\n";
}
you will no doubt see seven lines of output then the thrown error.
回答3:
because it reached EOF? You have 5 positive integers in your input, two times 0 (no output), and then EOF is reached.
来源:https://stackoverflow.com/questions/8209558/try-catch-throws-error