在 ss.clear() 之后使用 ss.str( " ") 用于新定义的字符串流

use of ss.str("") after ss.clear() for a newly defined string stream

本文关键字:ss 定义 字符串 新定义 str 之后 clear 用于      更新时间:2023-10-16

(学习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