c++sstream 简记-格式转换

最近在准备蓝桥杯的比赛,在历届真题中前面的几道题经常会让我想到使用格式之间的转化比如说将int转化为string使用string的函数来解题更方便些,所以这里一下这里的知识。

只讲用法:

引入sstream库。
在使用之前需要注意的事情:
即如果你在使用流对象的时候在数据量比较大的时候最好不要重复构造一个stringstream,这耗费的时间是比较多的,而你在迭代中使用同一个stringstream对象时一定要注意要使用clear方法清空流对象stream。如下:

#include <sstream>
#include <iostream>
int main()
{
    std::stringstream stream;
    int first, second;
    stream<< "456"; //插入字符串
    stream >> first; //转换成int
    std::cout << first << std::endl;
    stream.clear(); //在进行多次转换前,必须清除stream
    stream << true; //插入bool值
    stream >> second; //提取出int
    std::cout << second << std::endl;
} 

运行结果:

456
1

通用转换模板:

template<class out_type,class in_value>

out_type convert(const in_value &t)

{

stringstream stream;

stream<<t;//向流中传值

out_type result;//这里存储转换结果

stream>>result;//向result中写入值

return result;

}

例如:int转string

#include <string>
#include <sstream>
#include <iostream> 

int main()
{
    std::stringstream stream;
    std::string result;
    int i = 1000;
    stream << i; //将int输入流
    stream >> result; //从stream中抽取前面插入的int值
    std::cout << result << std::endl; // print the string "1000"
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值