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