字符串流stringstream的使用

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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值