(学习C++( 我一直在看下面的代码部分:
stringstream ss;
// more code
ss.clear();
ss.str("");
当ss.clear();
旨在删除字符串值时,为什么调用ss.str("");
?我打印出str()
值std::cout
,看到它的长度为零,没有行ss.str("");
那么为什么要包括它呢?
在我的研究中,我遇到了这个问题,@Johannes Schaub - litb 的公认答案也做了同样的事情。我错过了什么。
std::stringstream::clear()
继承自父类,并且 inheritage 源函数std::basic_ios::clear()
来自 CppReference(上面链接(:
通过为流错误状态标志分配状态值来设置它们。默认情况下,分配具有清除所有错误状态标志效果的
std::ios_base::goodbit
。
它不会清除stringstream
的内容,而是清除在以前的I/O操作中设置的所有错误标志(例如遇到EOF(。
清除字符串内容的实际语句是 ss.str("")
。
此示例演示了clear()
的功能:
using std::cout;
std::istringstream s("8");
int a;
s >> a;
cout << a; // Output: 8
a = 10;
s >> a;
cout << a << " " << s.eof(); // Output: 10 1
s.clear();
cout << s.eof() << " " << s.str(); // Output: 0 8
为什么是 ss.str("(;当 ss.clear((;是为了删除字符串值?
clear()
并不意味着删除字符串值。它旨在设置流状态标志。
stringstream ss;
ss<<1;
cout<<ss.str()<<endl; //prints 1
ss.clear(); // does not remove value from ss
cout<<ss.str()<<endl; //prints 1
ss.str(""); //this removes the value
cout<<ss.str(); //empty