tags:

views:

122

answers:

3
int i,j;

std::string s;

std::cin>>i>>j>>s>>s>>i;

std::cout<<i<<" "<<j<<" "<<s<<" "<<i;

Question Referring to the sample code above, what's the displayed output if the input string given is: "5 10 Sample Word 15 20"?

The answer is

15 10 Word 15

I have the question is what's the underline policy for cin to over write the existing values? Does the latter one simply overwrite the previous one? Is there any other situations?

I checked many books, but I didn't find one which explain this.

+12  A: 
std::cin >> i >> j >> s >> s >> i;

is equivalent to:

std::cin >> i;
std::cin >> j;
std::cin >> s;
std::cin >> s;  // overwrite previous s
std::cin >> i;  // overwrite previous i

Every time you read from cin to a variable, the old contents of that variable is overwritten.

So you are explicitly asking to overwrite s and i.

Shmoopty
A: 

When you "rewrote" to s, you destroyed the previous value of s. (which was SAMPLE). The reason i stayed the same is because the value of i was / remained 15 (you still overwrote i; however, you overwrote it with the same data, 15.)

Heidi
From the original question, 'input string given is: "5 10 Sample Word 15 20"'. The reason 'i' outputs the same value twice is that 'i' is not changed between outputs; that is, 'cout << i << ... << i' doesn't change the value of 'i' between writing.
atk
A: 

The >> notation makes this confusing, if you rewrite it as operator>>() it looks ugly but may help you understand how the function calls are working.

This line

std::cin >> i >> j >> s >> s >> i;

is equivalent to

std::cin.operator>>(i).operator>>(j).operator>>(s).operator>>(s).operator>>(i);

and the operator>>() for cin returns a reference to itself cin. So each step of the way is a separate call to the operator>>() of cin, guaranteed to be made in order from left to right.

Graphics Noob