c++ 常用数据类型转换

1、int型与string型的互相转换

int型转string型

    void int2str(const int &int_temp,string &string_temp)  
    {  
            stringstream stream;  
            stream<<int_temp;  
            string_temp=stream.str();   //此处也可以用 stream>>string_temp  
    }  

 string型转int型

    void str2int(int &int_temp,const string &string_temp)  
    {  
        stringstream stream(string_temp);  
        stream>>int_temp;  
    }  

在C++中更推荐使用流对象来实现类型转换,以上两个函数在使用时需要包含头文件 #include <sstream>,不仅如此stringstream可以实现任意的格式的转换如下所示:

template <class output_type,class input_type>
output_type Convert(const input_type &input)
{
    stringstream ss;
    ss<<input;
    output_type result;
    ss>>result;
    return result;
}

 stringstream还可以取代sprintf,功能非常的强大!

#include <stdio.h>
#include <sstream>

int main(){
    char *gcc= "gcc";
    int no = 1;

    std::stringstream stream;
    stream << gcc;
    stream << " is No ";
    stream << no;
    printf("%s\n", stream.str().c_str());
//重复使用前必须先重置一下,clear方法不如这个,但是值得注意的是使用stream的时候只是用str("")不能得到满意的答案我们需要我们需要将stringstream的所有的状态重置clear()
    stream.str(""); 
    stream << "blog";
    stream << ' ';
    stream << "is nice";
    printf("%s\n", stream.str().c_str());
    return 0;
}

 

 

 

  

posted @ 2018-09-18 15:55  yskn  阅读(1608)  评论(0编辑  收藏  举报