标签:
1. 使用itoa函数
#include <stdlib.h> #include <stdio.h> int main(void) { int number = 12345; char string[32]; itoa(number, string, 10); printf("integer = %d string = %s\n", number, string); return 0; }
2. 不利用库函数,转换为c风格的字符串
void intToString(int num, char*s) { int i = 0; while (num) { s[i] = num%10 + ‘0‘; num = num/10; i++; } s[i] = ‘\0‘; for (int j = 0, k = i-1; j < k; j++,k--) { char temp = s[j]; s[j] = s[k]; s[k] = temp; } }
3. 利用字符串流实现
string intToString(int n) { ostringstream ostr; ostr<<n; return ostr.str(); }
4. 利用string实现
string intToString2(int n) { string result = ""; while (n) { char c = n%10 + ‘0‘; result = c+result; n = n/10; } return result; }
还可以利用string得到char*指针
string str = intToString(n); char * s = const_cast<char*>(str.c_str());
标签:
原文地址:http://www.cnblogs.com/happygirl-zjj/p/4768037.html