简体   繁体   中英

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();
}

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, eg, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM