1、简单输入输出
#include<sstream>
#include<iostream>
using namespace std;
int main()
{
string line, word;
cout << "输入字符串:";
while (getline(cin, line))
{
stringstream stream(line);
cout << "输出字符串:";
cout << stream.str() << endl;
while (stream >> word){ cout << word << endl; }
}
return 0;
}
结论:以空格为分隔符输出子字符串
2、数字和字符串之间进行转换
将字符串输出到字符流内,然后根据不同的类型从字符流中输入到对应的变量中。
#include<sstream>
#include<iostream>
using namespace std;
int main()
{
int val1=200, val2 = 100;
stringstream ss;
ss << "val1: " << val1 << endl << "val2: " << val2 << endl;
cout << ss.str();
string s;
int a, b;
ss >> s >> a >> s >> b;
cout << a <<" "<< b << endl;
return 0;
}
3、释放内存
#include <cstdlib>
#include<iostream>
#include<sstream>
using namespace std;
int main()
{
stringstream ss;
string s;
ss << "hello sstream....";
ss >> s;
cout << "size of stream = " << ss.str().length() << endl;
cout << "s: " << s << endl;
ss.str("");
cout << "size of stream = " << ss.str().length() << endl;
}
4、从cin里读取一行
#include <cstdlib>
#include<iostream>
#include<sstream>
using namespace std;
int main()
{
string s;
while (getline(cin,s))
{
stringstream ss(s);
cout << ss.str() << endl;
}
}
5、读取txt文件
ifstream fin("data.txt");
string s;
string subs;
vector<int> ints;
int tmp;
while(getline(fin,s,'\n'))//getline函数默认是以\n作为一次读取的字符串多少
{
int pos0 = s.find(' ');
int pos1 = s.find(':');
subs = s.substr(pos0,pos1);
stringstream strs(subs);
strs>>tmp;
ints.push_back(tmp);
}