gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:48:51 27 4
gpt4 key购买 nike

(学习C++)我一直在看下面的代码部分:

stringstream ss;

// more code

ss.clear();
ss.str("");

为什么 ss.str(""); 调用时 ss.clear(); 是为了删除字符串值?我将 str() 值打印到 std::cout 并看到它的长度为零,没有行 ss.str(""); 那么为什么要包含它呢?

在我的研究中,我遇到了这个 question和@Johannes Schaub 接受的答案 - litb 做同样的事情。我错过了什么。

最佳答案

std::stringstream::clear()继承自父类,继承源函数为std::basic_ios::clear()

来自 CppReference(上面的链接):

Sets the stream error state flags by assigning them the value of state. By default, assigns std::ios_base::goodbit which has the effect of clearing all error state flags.

不会清除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

关于c++ - 在 ss.clear() 之后为新定义的字符串流使用 ss.str (""),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48333751/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com