简体   繁体   English

使用 ostringstream 而不是仅使用常规字符串有什么意义?

[英]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.我是第一次学习 C++ 套接字,我的示例大量使用 ostringstream。 What is the purpose and advantage of using stringstreams here instead of just using strings?在这里使用 stringstreams 而不是只使用字符串的目的和优势是什么? It looks to me in this example that I could just as easily use a regular string.在这个例子中,在我看来,我可以很容易地使用常规字符串。 Isn't using this ostringstream more bulky?使用这个 ostringstream 不是更笨重吗?

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.它们不等于字符数组,例如std::string ,它基本上是一个包含指向字符数组的指针的对象。 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.相比之下,字符串对象会有一些缺陷,例如,输出数字,缺乏像 endl 这样方便的函数,麻烦的连接,尤其是。 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.现在std::ostringstream是一个舒适且易于设置的缓冲区,用于格式化和准备文本形式(包括数字)的大量数据,以便进一步组合输出。 Moreover, in comparison to simple ostream object cout , you may have a couple of such buffers and juggle them as you need.此外,与简单的 ostream 对象cout ,您可能有几个这样的缓冲区并根据需要处理它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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