fredrik.eriksson

Coffee and a keyboard

stringstream is strange

I find the behavior of stringstream a bit strange If you take a look at the code bellow you would expect it to output foo, foobar, foobarbaz. Then the standard tells us that str() resets the stream position to 0 so we would expect foo, bar, baz.

#include <sstream>
#include <iostream>

using namespace std;

int main()
{
    stringstream ss("foo");
    cout << ss.str() << endl;
    ss << "bar";
    cout << ss.str() << endl;
    ss << "baz";
    cout << ss.str() << endl;
}

The standard also tells us that the the default constructor is passed ios_base::in | ios_base::out, so if tell the constructor to set the put pointer
to at-end we should get the expected behavior (see the end). So my conclusion is that stringstream may not be that strange if you know the intended behavior, but it’s still not obvious and will lead to errors.

stringstream ss("foo", ios_base::in | ios_base::out | ios_base::ate);

Not behaving as one would expect

Take a few minutes and look at the code bellow. What do you think the compiled program would output.

#include <iostream>

using namespace std;

char const* test(char const* buf)
{
    cout << "const" << endl;

    return buf+6;
}

char* test(char* buf)
{
    cout << "mutable" << endl;

    return buf+6;
}

int main(int argc, char* argv[])
{
    char a1[] = "World Hello";
    char const a2[] = "Hello World";

    cout << test(a1)    << '\n'
         << a1          << '\n'
         << test(a2)    << '\n'
         << a2          << endl;

    return 0;
}

This is the output:

$ ./gcc-outconstmutableHelloWorld HelloWorldHello World$ ./intel-outmutableHelloWorld HelloconstWorldHello World

Note: VC++ 8.0 have the same output as the Intel C++ compiler.