3

I am learning C++ sockets for the first time, and my example uses ostringstream a lot. What is the purpose and advantage of using stringstreams here instead of just using strings? It looks to me in this example that I could just as easily use a regular string. Isn't using this ostringstream more bulky?

std::string NetFunctions::GetHostDescription(cost sockaddr_in &sockAddr)
{
    std::ostringstream stream;
    stream << inet_ntoa(sockAddr.sin_addr) << ":" << ntohs(sockAddr.sin_port);
    return stream.str();
}
user3685285
  • 6,066
  • 13
  • 54
  • 95
  • 3
    Possible duplicate of [c++ std::ostringstream vs std::string::append](http://stackoverflow.com/questions/19844858/c-stdostringstream-vs-stdstringappend) – Eli Sadoff Nov 07 '16 at 16:45
  • 3
    Write the equivalent code with `std::string`. I doubt you will save much. Usually the advantage of a `stringstream` is that you can easily replace it with `cout` or an `fstream` later. – nwp Nov 07 '16 at 16:47
  • You'd need more manual conversions if you used `std::string`. The `<<` overloads are very convenient. – molbdnilo Nov 07 '16 at 16:54
  • 1
    _"It looks to me in this example that I could just as easily use a regular string."_ Give it a try then come back to us and say whether you still hold this position. – Lightness Races in Orbit Nov 07 '16 at 16:58
  • You are looking at it at the client end. What if the function is one you didn't write, and it requires a `std::ostream` but you want to see the results in a string (and not, say, the console)? You can't give it a `std::string`, can you? – PaulMcKenzie Nov 07 '16 at 17:20

1 Answers1

2

Streams are buffers. They are not equal to char arrays, such as std::string, which is basically an object containing a pointer to an array of chars. Streams have their intrinsic functions, manipulators, states, and operators, already at hand. A string object in comparison will have some deficiencies, e.g., with outputting numbers, lack of handy functions like endl, troublesome concatenation, esp. with function effects (results, returned by functions), etc. String objects are simply cumbersome for that.

Now std::ostringstream is a comfortable and easy-to-set buffer for formatting and preparation of much data in textual form (including numbers) for the further combined output. Moreover, in comparison to simple ostream object cout, you may have a couple of such buffers and juggle them as you need.

Mykola Tetiuk
  • 153
  • 1
  • 13