首页 > 系统服务 > 详细

Linux int型转换为char*型几种方法总结

时间:2020-04-15 13:47:36      阅读:97      评论:0      收藏:0      [点我收藏+]

 一 前记

  这种转换,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;  
}

 

Linux int型转换为char*型几种方法总结

原文:https://www.cnblogs.com/dylancao/p/12704048.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!