#include《sstream》
istringstream类用于执行C++风格的串流的输入操作。
ostringstream类用于执行C风格的串流的输出操作。
strstream类同时可以支持C风格的串流的输入输出操作。
#include<iostream>
#include<sstream> //istringstream 必须包含这个头文件
#include<string>
using namespace std;
int main()
{
string str;
cin>>str;
istringstream ss(str);
string s;
while(ss >> s)
{
cout<<s<<endl;
}
}
输入: the sky is blue
输出:
the
sky
is
blue
经常用于字符串倒置等
注意的坑:
当istringstream到达输入流的末尾的时候,会发生什么?
看下面这段代码
#include<iostream>
#include<sstream>
#include<string>
using namespace std;
int main()
{
string data = "1 2 3 ";
istringstream in(data);
string part;
for (int i = 0; i < 5; i++)
{
cout << "in>>part: " << (in >> part) << endl;
cout << part << endl;
}
return 0;
}
结果
in>>part: 0x7fff296452b8
1
in>>part: 0x7fff296452b8
2
in>>part: 0x7fff296452b8
3
in>>part: 0
3
in>>part: 0
3
1.
cin>>part变为0
2.
cin已经关闭,part后续没有被赋值

本文深入探讨了C++中istringstream、ostringstream及strstream类的功能与应用,详细解析了这些串流类如何处理输入输出操作,包括字符串的读取、倒置等常见操作。特别关注istringstream在处理输入流末尾时的行为特性。
580

被折叠的 条评论
为什么被折叠?



