Why does stringstream not move to next set of characters when cout?

string inputLine = "1 2 3";
stringstream stream(inputLine);

// Case One
int x, y, z;
stream >> x;
stream >> y;
stream >> z;
// x, y, z have values 1, 2, 3

// Case Two
cout << stream << endl;
cout << stream << endl;
cout << stream << endl;
// All 3 print out 1

For the above code, why is it when you assign to an int, stringstream moves to the next set of characters, but not with cout?

Actual code: I'm compiling this on a mac using g++

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

using namespace std;

int main(int argc, char *argv[])
{
    string inputLine = "1 2 3";

    stringstream stream(inputLine);

    // Case One
    int x, y, z;
    stream >> x;
    stream >> y;
    stream >> z;
    // x, y, z have values 1, 2, 3

    // Case Two
    cout << stream << endl;
    cout << stream << endl;
    cout << stream << endl;
}

This shouldn't compile but does due to a bug (#56193) in your standard library implementation, which is not fully C++11-compliant.

The stream is converting to a bool representing its state; cout is printing 1 for true .

  • Change your integers and you'll see the output is still 1 .
  • Or, add std::boolalpha to std::cout and you'll see true instead of 1 .
  • The crux of it is that your std::cout << stream is not actually printing anything relating to the contents of the stream buffer. That's not how you extract data from a stream.

    链接地址: http://www.djcxy.com/p/92248.html

    上一篇: 返回类型与自动和朋友功能匹配

    下一篇: 为什么stringstream在cout时不会移动到下一组字符?