C++:字符串流有什么好处?
谁能告诉我一些在c++中使用字符串流的实际例子,即使用流插入和流提取运算符输入和输出到字符串流?
could any one tell me about some practical examples on using string streams in c++, i.e. inputing and outputing to a string stream using stream insertion and stream extraction operators?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用字符串流将任何实现
operator <<
的内容转换为字符串:甚至
You can use string streams to convert anything that implements
operator <<
to a string:or even
我主要将它们用作内存缓冲区,用于创建消息:
或构造复杂的字符串:
它很有用,因为它为使用字符缓冲区带来了 std::stream 的所有可扩展性(ostreams 扩展性和区域设置支持,缓冲内存管理被隐藏等等)。
我见过的另一个例子是 gsoap 库中使用依赖项注入的错误报告: soap_stream_fault 采用 ostream&报告错误消息的参数。
如果需要,可以传递 std::cerr、std::cout 或 std::ostringstream 实现(我将其与 std::ostringstream 实现一起使用)。
I use them mostly as memory buffers, in creating messages:
or to construct complex strings:
It is useful because it brings all the extensibility of
std::stream
s to using character buffers (ostreams extensibility and locales support, buffer memory management is hidden and so on).Another example I've seen was the error reporting in gsoap library, using dependency injection: soap_stream_fault takes an ostream& parameter to report error messages in.
If you want you can pass it std::cerr, std::cout or an std::ostringstream implementation (I use it with a std::ostringstream implementation).
它们可以在任何可以使用普通流的地方使用。
因此,在从文件读取的情况下,您可能会从字符串流中读取。
They can be used anywhere a normal stream can be used.
So in situations where you were reading from a file you could potentially read from a string stream.
除了优点之外,还有一点如果您使用 gcc 4.3.1,请仔细考虑。我没有检查以前版本的 gcc。
Besides advantages there is one point to carefully consider if you use gcc 4.3.1. I didn't checked preceding versions of gcc.