一:直接编写函数实现:
1#include <iostream>
2using namespace std;
3
4string 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
20int main()
21
22{
23 cout<<intTostr(-235)<<endl; //Test case
24 return 0;
25}
26
二 利用库函数实现:
sprintf :
1sprintf:
2void PrettyFormat(int i, char * ch){
3 sprintf(ch, "%d",i);
4}
5易用且有效率。但不安全,且不易用在模板中,exception c++ style中herb sutter建议不要用sprintf;
6
利用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;
}
还可以使用: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();
}
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();
return result;
}
void PrettyFormat(int i, string& s) {
// Perhaps the neatest and simplest yet, if it's all you need:
s = lexical_cast<string>(i);
}
这个不错,可每用过boost