简体   繁体   中英

Calling cin.get() twice: unexpected result?

So I was playing around with cin.get() to try and understand it more thoroughly.

char x[20];
cout << "Enter a name: ";
cin >> x;
cout << cin.get();

If I enter "Bob Smith", it outputs 32 - the ASCII number for space - which I expected as it's the character after the input stream.

char x[20];
cout << "Enter a name: ";
cin >> x;
cout << cin.get() << " " << cin.get()

However, this outputs "83 32", which confuses me. Why does it reverse the order to output "S" before space?

If you change cout << cin.get() << " " << cin.get() to the following code:

cout << cin.get();
cout << " " << cin.get();

It prints 32 83 , which is not reversed.

This is because if you put two conditions in one line, C++ might not evaluate them in order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM