一:直接编写函数实现:
1
#include <iostream>
2
using namespace std;
3![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
4
string intTostr(int num)
5
{
6
if (num==0) return "0";
7
string str="";
8
int num_=num>0?num:-1*num;
9
while (num_)
10
{
11
// cout<<(char)(num_%10+48);
12
str=(char)(num_%10+48)+str;
13
num_=num_/10;
14
}
15
if (num<0)
16
str='-'+str;
17
return str;
18
}
19![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
20
int main()
21![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
22
{
23
cout<<intTostr(-235)<<endl; //Test case
24
return 0;
25
}
26![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
二 利用库函数实现:
sprintf :
1
sprintf:
2
void PrettyFormat(int i, char * ch){
3
sprintf(ch, "%d",i);
4
}
5
易用且有效率。但不安全,且不易用在模板中,exception c++ style中herb sutter建议不要用sprintf;
6![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
利用snprintf取代,
int _snprintf( char *buffer, size_t count, const char *format [, argument] ... ); // more safe
char sa[256];
sa[sizeof(sa)-1]=0;
_snprintf(sa,sizeof(sa),"%s",sb);
if(sa[sizeof(sa)-1]!=0)
{
printf("warning:string will be truncated");
sa[sizeof(sa)-1]=0;
}
![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
还可以使用:itoa:
char * itoa( int value, char *string, int radix ); <cstdlib>
例如: itoa(i, buf, 10);
stringstream:
void PrettyFormat(int i, string& s) {
// Not quite as neat and simple:
ostringstream temp;
temp << setw(4) << i;
s = temp.str();
}
![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
boost::lexical_cast:
template<typename Target, typename Source>
Target lexical_cast(Source arg) {
std::stringstream interpreter;
Target result;
if(!(interpreter << arg) || !(interpreter >> result) || !(interpreter >> std::ws).eof())
throw bad_lexical_cast();
![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
return result;
}
![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
void PrettyFormat(int i, string& s) {
// Perhaps the neatest and simplest yet, if it's all you need:
s = lexical_cast<string>(i);
}
![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
这个不错,可每用过boost
![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)