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());

    stream.str(""); ///重复使用前必须先重置一下
    stream << "blog";
    stream << ' ';
    stream << "is nice";
    printf("%s\n", stream.str().c_str());
    return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/yskn/p/9669422.html
今日推荐