sstream数据类型转换的使用方法

#include<iostream>
#include<algorithm>
#include<sstream>

using namespace std;

int main(){
	//字符串转数字
	//方法1
	stringstream ss;
	string s="1234";
	int i;
	ss<<s;
	ss>>i;
	cout<<i<<endl;
	
	//方法2 
	//stoi(字符串,起始位置,n进制),将n进制的字符串转化为十进制
	int j=stoi(s); 	//不写默认为十进制 
	cout<<j<<endl;
	
	int k=stoi("1010",0,2);
	cout<<k<<endl;
	
	ss.clear();		//不clear会出错 
	
	//数字转字符串 
	//方法1
	int a=233;
	string out;
	ss<<a;
	ss>>out;
	cout<<out<<endl;
	
	//方法2 
	cout<<to_string(a)<<endl;
	
	//字符串转化为其他类型 
	string test="-123 9.87 welcome to, 989, test!";
	istringstream iss;
	iss.str(test);
	string s1;
	cout<<"按照空格读取字符串"<<endl;
	while(iss>>s){
		cout<<s<<endl;	//按空格读取string 
	}
	
	istringstream strm(test);
	int ii;
	float f;
	char c;
	char buff[1024];
	
	strm>>i;
	cout<<"读取int类型"<<ii<<endl;
	strm>>f;
	cout<<"读取float类型"<<f<<endl;
	strm>>c;
	cout<<"读取char类型"<<c<<endl;
	strm>>buff;
	cout<<"读取buffer类型"<<buff<<endl;
	
	strm.ignore(100,',');
	int m;
	strm>>m;
	cout<<"忽略,读取int类型:"<<m<<endl;
	
	//多个字符串拼接
	stringstream sstream;
	sstream<<"first"<<" "<<"string,";
	sstream<<" second string";
	cout<<"strResult is:"<<sstream.str()<<endl;
	
	//清空sstream
	sstream.str("");
	sstream<<"third string";
	cout<<"After clear, strResult is:"<<sstream.str()<<endl; 
	return 0;
} 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值