C++ stringstream的使用,实现任何数据转换

stringstream可以吞下任何类型,根据实际需要吐出不同的类型。

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    string str1;
    int i;
    cin >> str1;
    stringstream ss;
    ss << str1;
    ss >> i;
    cout << i;

    return 0;
}
  • 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;
}

Alt

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

重复利用stringstream对象

如果你打算在多次转换中使用同一个stringstream对象,记住再每次转换前要使用clear()方法;

在多次转换中重复使用同一个stringstream(而不是每次都创建一个新的对象)对象最大的好处在于效率。stringstream对象的构造和析构函数通常是非常耗费CPU时间的。

详细介绍:
https://www.cnblogs.com/wuchanming/p/3906176.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值