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
you are detecting eof too. Read up on
.good(),.bad(),.eof()and.fail(): http://www.cplusplus.com/reference/iostream/ios_base/iostate/Try this:
If you prefer getting the exception, try
Loose notes:
.