Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of using ostringstream instead of just using a regular string?

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();
}
like image 874
user3685285 Avatar asked Sep 06 '25 14:09

user3685285


1 Answers

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.

like image 65
Mykola Tetiuk Avatar answered Sep 09 '25 10:09

Mykola Tetiuk