1、之前刷leetcode发现这个函数对于对单词的计数很好用,总是忘记怎么用,自己总结记录一下。
2、头文件 #include <sstream>
3、<sstream> 定义了三个类:istringstream、ostringstream 和 stringstream,分别用来进行流的输入、输出和输入输出操作,也就是in out 。
5、流输出举例
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string str;
str = "hello i am lv";
stringstream ss(str);
//我如果要计算长度的话
int count = 0;
while (ss >> str)//这里用了流输出
{
count++;
}
cout << count << endl;//这里会输出4
ss.str("");//字符串清空
return 0;
}
在这里面我可以使用字符串初始化流输入输出类型。
6、流输入举例
#include <iostream>
#include <sstream>
#include <algorithm>
using namespace std;
int main()
{
string str;
str = "hello i am lv";
stringstream ss;
ss << str;
str = "hello i am bin";
ss << str;
//cout << ss << endl;//这里我们不能直接输出流类型的要用str()转换成string类型才能输出
cout << ss.str() << endl;//这里就会输出hello i am lvhello i am bin
return 0;
}
7、多次转换需要使用clear()清除
#include <iostream>
#include <sstream>
#include <algorithm>
using namespace std;
int main()
{
string str;
str = "147222";
stringstream ss;
ss << str;
//cout << ss << endl;//这里我们不能直接输出流类型的要用str()转换成string类型才能输出
cout << ss.str() << endl;//这里就会输出hello i am lvhello i am bin
ss.clear();
int i;
ss >> i;
cout << i << endl;
return 0;
}
总结:stringstream这个类型对于单词来说很好用。