gpt4 book ai didi

c++ - 如何使用相同的 stringstream 对象标记两个不同的字符串?

转载 作者:太空狗 更新时间:2023-10-29 21:24:43 24 4
gpt4 key购买 nike

如何使用相同的 stringstream 对象标记两个不同的字符串?

我正在尝试以下代码,但它不起作用:

using namespace std;

void check()
{
stringstream s( "This is a test");
string token;

while (s>>token)
{
cout<< token <<'\n';
}
s.str("hello world");
while ( s>> token )
{
cout<< token <<'\n';
}
}

int main()
{
check();
int z;
cin>>z;
}

最佳答案

您需要通过执行 s.clear(); 来重置流标志:

stringstream my_stringstream( "This is a test");
string token;

while ( my_stringstream >> token )
{
cout<< token <<'\n';
}

my_stringstream.str("hello world");
my_stringstream.clear();

while ( my_stringstream >> token )
{
cout<< token <<'\n';
}

当您在第一个 while 循环中使用 >>> 到达流的末尾时设置 eof 位。这就是为什么您需要调用 clear() 来重置流,如答案中所示。
感谢 Jesse Good 的补充。

关于c++ - 如何使用相同的 stringstream 对象标记两个不同的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15376535/

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