我是靠谱客的博主 执着书包,最近开发中收集的这篇文章主要介绍,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

<sstream>

template<class T>

 

void to_string(string & result,const T& t)

 

{

 

    ostringstream oss;//创建一个流

 

oss<<t;//把值传递如流中

 

result=oss.str();//获取转换后的字符转并将其写入result

 }

 

这样,你就可以轻松地将多种数值转换成字符串了:

 

to_string(s1,10.5);//doublestring

 

to_string(s2,123);//intstring

 

to_string(s3,true);//boolstring

 

可以更进一步定义一个通用的转换模板,用于任意类型之间的转换。

函数模板convert()含有两个模板参数out_type和in_value,功能是将in_value值转换成out_type类型:

 

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;

}

这样使用convert()

double d;

string salary;

string s=”12.56”;

d=convert<double>(s);//d等于12.56

salary=convert<string>(9000.0);//salary等于”9000”

在过去留下来的程序代码和纯粹的C程序中,传统的<stdio.h>形式的转换伴随了我们很长的一段时间。但是,如文中所述,基于stringstream的转换拥有类型安全和不会溢出这样抢眼的特性,使我们有充足得理由抛弃<stdio.h>而使用<sstream><sstream>库还提供了另外一个特性可扩展性。你可以通过重载来支持自定义类型间的转换。

一些实例:

stringstream通常是用来做数据转换的。

相比c库的转换,它更加安全,自动和直接。

例子一:基本数据类型转换例子 intstring

#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"

 

 

例子二:除了基本类型的转换,也支持char *的转换。 

#include <sstream>
#include <iostream> 


int main()
{
    std::stringstream stream;
    char result[8] ;
    stream << 8888; 
//stream中插入8888
    stream >> result; //抽取stream中的值到result
    std::cout << result << std::endl; // 屏幕显示 "8888"

 

例子三:再进行多次转换的时候,必须调用stringstream的成员函数clear()

#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;

最后

以上就是执着书包为你收集整理的的全部内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(44)

评论列表共有 0 条评论

立即
投稿
返回
顶部