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

 

 

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM