Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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;
}
like image 859
apjak Avatar asked Jun 17 '16 14:06

apjak


1 Answers

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.

like image 125
Lightness Races in Orbit Avatar answered Oct 07 '22 04:10

Lightness Races in Orbit