如何清除stringstream变量? [英] How do you clear a stringstream variable?

查看:215
本文介绍了如何清除stringstream变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已尝试过几种方法,

  std :: stringstream m; 
m.empty();
m.clear();

两者都不起作用。

解决方案

对于所有标准库类型,成员函数 empty()是一个查询,而不是命令,你空吗?



clear()成员函数继承自 ios ,用于清除流的错误状态,例如如果文件流的错误状态设置为 eofbit (文件结束),则调用 clear()将会将错误状态设置为 goodbit (无错误)。



清除 stringstream ,使用:

  m.str虽然使用:



<$ p

$ p> m.str(std :: string());

在技术上更高效,因为你避免调用 std :: string 构造函数 const char * 。但是任何编译器,今天应该能够生成相同的代码在这两种情况下 - 所以我只是去与更容易阅读。


I've tried several things already,

std::stringstream m;
m.empty();
m.clear();

both of which don't work.

解决方案

For all the standard library types the member function empty() is a query, not a command, i.e. it means "are you empty?" not "please throw away your contents".

The clear() member function is inherited from ios and is used to clear the error state of the stream, e.g. if a file stream has the error state set to eofbit (end-of-file), then calling clear() will set the error state back to goodbit (no error).

For clearing the contents of a stringstream, using:

m.str("");

is correct, although using:

m.str(std::string());

is technically more efficient, because you avoid invoking the std::string constructor that takes const char*. But any compiler these days should be able to generate the same code in both cases - so I would just go with whatever is more readable.

这篇关于如何清除stringstream变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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