tags:

views:

139

answers:

1
+4  Q: 

C++ cin questions

This seems to be weird:

int main(int argc, char* argv[]) {  

    cout << "function main() .." << '\n';  

    char ch = 0;  
    double number_value=1.1;  

    cin >> ch;  
    cin.putback(ch);  

    cin >> number_value;  
    cout << "1 .. " << " " << cin.good() << " " << number_value << '\n';  
    cin >> number_value;  
    cout << "2 .. " << " " << cin.good() << " " << number_value << '\n';  

    return 0;  

}  

If I input the following:

7a 1  

I get the following:

function main() ..

7a 1  
1 ..  1 7  
2 ..  0 0  

I understand the:

1 ..  1 7 

but why the variable number_value is 0. cin.good() shows failure so nothing would have read and the value in number_value from the previous assignment would remain. I expect the value of 7.

+2  A: 

That's what I'd expect too. With the compilers I have handy, the output looks like this:

function main() ..
7a
1 ..  1 7
2 ..  0 7

You may have discovered a bug in your compiler's standard library.

Jerry Coffin
Second that output with MinGW... function main()\n 7a 1\n 1 .. 1 7\n 2 .. 0 7\n
Not changing the value is required: 22.2.2.1.2/1 "If an error occurs, val is unchanged; otherwise it is set to the resulting value."
Roger Pate