Why use a stringstream when you can use string.append?

So far, I've identified two uses, thanks to someone else:
-Unit tests
-Conversions to/from strings.
Since a stringstream is a stream object, any overloaded stream insertion or extraction operator will work on stringstreams too. An example could be:

1
2
3
4
5
6
7
8
9
10
11
struct Coord
{
    double x;
    double y;
}

std::ostream& operator<<(ostream& os, const Coord& coord)
{
    os << "(" << coord.x << "," << coord.y << ")";
    return os;
}


Even though overloading these operators as such is usually used for cout, cerr and cin, they will work on all streams. This includes stringstreams as well.
Your question is a little bit ambiguous. It could mean "Why is there such a thing as a stringstream because string.append can be used to do almost everything that a stringstream can do?" or it could mean "Why would I use a stringstream in a situation where string.append would work?"

The One answer to the second is, like you said, conversion to strings. If I want to generate a string that includes a counter, I use a std::ostringstream to create it. If I merely want to concatenate 2 strings, I use append (actually, I use operator+).

The answer to the first is, you're looking at stringstream incorrectly. stringstream is not a glorified string, it's a specialized stream. Any place you need to use a std::istream, you can use a std::istringstream. And the same goes for std::ostringstream. The fact that you can do something that works similarly to std::string.append is because of a similarity between the functionality of append and the insertion operator, not because there is a std::string undergirding the std::ostringstream class.

Edit: Clarified first part of answer
Last edited on
string interface is not the same as stringstream interface.

one has member functions which other does not, and supports a wide range of capabilities that the other does not and vice versa.

if you use string just to append another string to the string then your question makes sense.
but even in that case where you do not care about interface, there is a difference of underlying code "overhead".

Last edited on
Topic archived. No new replies allowed.