C++中从整形转换到字符串型(int to string)
1.用c++编写一个函数的方式:
string convertInt(int number)
{
if (number == 0)
return "0";
string temp="";
string returnvalue="";
while (number>0)
{
temp+=number%10+48;
number/=10;
}
for (int i=0;i<temp.length();i++)
returnvalue+=temp[temp.length()-i-1];
return returnvalue;
}
2.通过stringstream做中间转换,C++头文件在<sstream>中,C头文件在<sstream.h>中
string convertInt(int number)
{
stringstream ss;//create a stringstream
ss << number;//add number to the stream
return ss.str();//return a string with the contents of the stream
}
3.通过boost库lexical_cast
#include <boost/lexical_cast.hpp>
string s = boost::lexical_cast<string>( number );