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 .
1 . 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.
上一篇: 返回类型与自动和朋友功能匹配
