Fork me on GitHub

 一 前记

  这种转换,windows下最常用就是atoi()函数。可惜的是,在Linux中没有itoa()函数,只有atoi()   这点很有趣,居然不对称。

所以在Linux中实现从整型到char*的转换,一般使用如下两种方法:

 

二 用sprintf()函数来实现

 

 sprintf(char * cValue, "%d",  int nValue);

这种方法简单易行,笔者比较喜欢,下面看一个例子:

 

#include <stdio.h>
#include <stdlib.h>

int main()
{
        int a = 3333;
        char test[5];
        sprintf(test,"%d ",a);
        printf("string is:%s ",test);

        return 0;
}

 

三 自定义函数进行转换

 

  这种实现方法很多,这里就给出一个例子仅供参考:

 

#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
  
int main()  
{  
    int number, i;  
    char str[10];  
  
    while(scanf("%d", &number) != EOF)  
    {  
        memset(str, 0, sizeof(str));  
      
        i = 0;  
        while(number)  
        {  
            str[i ++] = number % 10 + '0';  
            number /= 10;  
        }         
        puts(str);        
    }  
  
    return 0;  
}

 

posted on 2020-04-15 11:19  虚生  阅读(2994)  评论(0编辑  收藏  举报