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.