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.
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
.
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.
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.)
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.