4

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();
}
5
  • 3
    Possible duplicate of c++ std::ostringstream vs std::string::append Commented Nov 7, 2016 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. Commented Nov 7, 2016 at 16:47
  • You'd need more manual conversions if you used std::string. The << overloads are very convenient. Commented Nov 7, 2016 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. Commented Nov 7, 2016 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? Commented Nov 7, 2016 at 17:20

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.