C语言整型转字符串

int 2 string

弯路

网上一般查到会说用itoa函数,

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdlib.h>
#include <stdio.h>
int main()
{
int number1 = 123456;
int number2 = -123456;
char string[16] = {0};
itoa(number1,string,10);
printf("数字:%d 转换后的字符串为:%s\n",number1,string);
itoa(number2,string,10);
printf("数字:%d 转换后的字符串为:%s\n",number2,string);
return 0;
}

像菜鸟教程都这样教, 不过itoa不是基础库函数而且不符合C99标准, 编译时候直接报警

1
2
3
4
5
6
7
8
9
main.c:13:13: warning: implicit declaration of function 'itoa' is invalid in C99 [-Wimplicit-function-declaration]
itoa(n, pr, 10);
^
1 warning generated.
Undefined symbols for architecture x86_64:
"_itoa", referenced from:
_main in main-2e9155.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

正道

后面找到用sprintf

1
2
3
4
5
6
7
8
9
10
#include<stdio.h>  
#include<stdlib.h>

void main (void)
{
int num = 100;
char str[25];
sprintf(str, " %d" , num);
printf ("The number 'num' is %d and the string 'str' is %s. \n" ,num, str);
}

补充

不过遇到比较长的整型时候, 发现疑似溢出的情况(像这个负号)

1
2
3362695274           // 输入
- 9 3 2 2 7 2 0 2 2 // 输出(每个数字中间加了空格))

其实是整型应该从int换成long, 然后就正常了

1
2
3
4
5
6
7
8
int main()
{
char str[10];
long x = 1234567890L;
sprintf(str,"%ld",x);
printf("%s",str);
return 0;
}

参考: