istringstream,ostringstream和stringstream之间有什么区别? /为什么不使用stringstream在每种情况? [英] What's the difference between istringstream, ostringstream and stringstream? / Why not use stringstream in every case?

查看:749
本文介绍了istringstream,ostringstream和stringstream之间有什么区别? /为什么不使用stringstream在每种情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我何时使用 std :: istringstream std :: ostringstream std :: stringstream ,为什么我不应该在每个场景中使用 std :: stringstream (是否有任何运行时性能问题? p>

最后,这是否有什么坏处(而不是使用流):

  std :: string stHehe(Hello); 

stHehe + =stackoverflow.com;
stHehe + =!;


解决方案

我个人觉得很少流入和流出同一字符串流。



通常我想从一个字符串初始化一个流,然后解析它;



如果你在同一个流中进行流式传输,你必须非常小心地使用一个字符串流,然后提取结果并存储它。流状态和流位置。



使用'just' istringstream ostringstream 更好地表达你的意图,并给你一些检查愚蠢的错误,如意外使用< vs > / code>。



可能有一些性能改进,但我不会先看。

你写的没有什么问题。如果你发现它的表现不够好,你可以剖析其他方法,否则坚持什么是最清晰的。个人而言,我只是去:

  std :: string stHehe(Hello stackoverflow.com! 


When would I use std::istringstream, std::ostringstream and std::stringstream and why shouldn't I just use std::stringstream in every scenario (are there any runtime performance issues?).

Lastly, is there anything bad about this (instead of using a stream at all):

std::string stHehe("Hello ");

stHehe += "stackoverflow.com";
stHehe += "!";

解决方案

Personally I find it very rare that I want to preform streaming into and out of the same string stream.

Usually I want to either initialize a stream from a string and then parse it; or stream things too a string stream and then extract the result and store it.

If you're streaming to and from the same stream you have to be very careful with the stream state and stream positions.

Using 'just' istringstream or ostringstream better expresses your intent and gives you some checking against silly mistakes such as accidental use of << vs >>.

There might be some performance improvement but I wouldn't be looking at that first.

There's nothing wrong with what you've written. If you find it doesn't perform well enough then you could profile other approaches, otherwise stick with what's clearest. Personally, I'd just go for:

std::string stHehe( "Hello stackoverflow.com!" );

这篇关于istringstream,ostringstream和stringstream之间有什么区别? /为什么不使用stringstream在每种情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆