donutbomb
donutbomb

Reputation: 5

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?

Upvotes: 0

Views: 92

Answers (1)

Vincent Thacker
Vincent Thacker

Reputation: 393

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.

Upvotes: 2

Related Questions