Reputation: 193
I wanted to test behavior of std::cin
when an unexpected input is given. Why does std::cin
return 0 and 2.07386e-317 in a non-deterministic way?
#include <iostream>
using namespace std;
int main(){
double foo, bar;
while(cin.good() and cin >> foo >> bar){
cout << foo << " " << bar << endl;
}
if (cin.eof()){
cout << "Ooops, EOF encountered.\n";
}
else{
cout << "Something weird happened!\n";
cout << foo << " " << bar << endl;
}
return 0;
}
Whenever I type,
<a_number> <non-number>
Output is <a_number> 0
And whenever I type,
<non-number> <anything>
Output is 0 2.07386e-317
I tried exact code by increasing number of input to 3 and,
<non-number> <non-number> <non-number>
Output is 0 0 2.07353e-317
For 4 inputs,
`<non-number> <non-number> <non-number> <non-number>`
Output is 0 2.07353e-317 0 2.07353e-317
Lastly, for 5 inputs,
`<non-number> <non-number> <non-number> <non-number> <non-number>`
Output is 0 2.07353e-317 2.07353e-317 0 2.07353e-317
I looked at the November 2014 working draft of current standart (C++14) and couldn't see any helpful information on this at § 27.4.2 where Narrow stream objects are explained in a surprisingly short way. I expected to see internal working details of std::cin
. Am I missing something?
I am curious about the reasons of behavior. Appreciate the help.
Upvotes: 1
Views: 237
Reputation: 782785
You shouldn't try to print the variables in the "Something weird happened" case, because that means the variable extraction wasn't successful. Any of the variables starting from the first incorrect input will not have been assigned.
See How to test whether stringstream operator>> has parsed a bad type and skip it for how you can skip over bad inputs.
Upvotes: 2