C语言整型转字符串

int 2 string

弯路

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

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

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

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

正道

后面找到用sprintf

1
#include<stdio.h>  
2
#include<stdlib.h>
3
4
void main (void)
5
{
6
    int num = 100;
7
    char str[25];
8
    sprintf(str, " %d" , num);
9
    printf ("The number 'num' is %d and the string 'str' is %s. \n" ,num, str);
10
}

补充

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

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

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

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

参考: