简体   繁体   中英

stringstream operator>> stop issues

I have the following code which runs out of my expectation, but I cannot figure out why.

stringstream ss1("01"), ss2("1");
int v1, v2;
while (ss1 >> v1 && ss2 >> v2 && v1 == v2) {}
if (ss1 && !ss2)
    cout << 1;
else if (!ss1 && ss2)
    cout << -1; // <== this line will execute
else
    cout << 0;

I expected the result would be cout << 0 , but it executes the line cout << 1 , which means !ss1 && ss2 is true .

Since !ss1 && ss2 is true , it means ss2 has not yet stopped. For checking that, I added another two lines so that the code becomes

stringstream ss1("01"), ss2("1");
int v1, v2;
while (ss1 >> v1 && ss2 >> v2 && v1 == v2) {}
while (ss2 >> v2)                 // these two lines are added to check 
    cout << "v2: " << v2 << endl; // whether ss2 really goes to the end.
if (ss1 && !ss2)
    cout << 1;
else if (!ss1 && ss2)
    cout << -1;
else
    cout << 0; 

However, the line cout << "v2: " << v2 << endl; didn't run.

So could anyone indicate where the problem is?

Let's go through the while loop:

  1. ss1 >> v1 gets executed, result is true ( v1 == 1 )
  2. ss2 >> v2 gets executed, result is true ( v2 == 1 )
  3. v1 == v2 gets executed, result is true
  4. The loop body is executed (nothing happens, it is empty)
  5. ss1 >> v1 gets executed, result is false , because there are no more int s in ss1

This means that the rest of the condition will not get executed, because what's the point? The while loop will not repeat, because one value is already false . This is called .

ss1 failed extraction, so it will return false , but ss2 never tried extraction, so it returns true , hence your output: -1 .

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