1.使用itoa函数
itoa()原型: char *itoa( int value, char *string,int radix);
原型说明:
输入参数:
value:要转换的数据。 string:目标字符串的地址。 radix:转换后的进制数,可以是10进制、16进制等,范围必须在 2-36。 功能:将整数value 转换成字符串存入string 指向的内存空间 ,radix 为转换时所用基数(保存到字符串中的数据的进制基数)。
返回值:函数返回一个指向 str,无错误返回。
注意:itoa不是一个标准的c函数,他是windows特有的,跨平台写程序,要用sprintf。
实现方法:
#include "stdafx.h" #include<stdio.h> #include"stdlib.h" #include<iostream> #include<ctype.h> using namespace std; int main() { int number = 12345; char stri[7]; _itoa_s(number,stri,10); cout <<number<<" "<<stri<<endl; system("pause"); return 0; }2.采用加’0‘再逆序的方法
实现方法
#include "stdafx.h" #include<iostream> #include<stdio.h> int main() { int num = 12345, j = 0, i = 0; char temp[7], str[7]; while (num) { temp[i] = num % 10 + '0'; i++; num = num / 10; } temp[i] = 0; printf("temp=%s\n",temp); i = i - 1; printf("temp=%d\n",i); while (i >= 0) { str[j] = temp[i]; i--; j++; } str[j] = '\0'; printf("string=%s\n",str); system("pause"); return 0; }