想整型转换为字符串没有itoa功能 [英] Want to Convert Integer to String without itoa function
本文介绍了想整型转换为字符串没有itoa功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想转换 INT为char
*在C时不使用 itoa()
功能。
i want to convert int to char
* in C without using itoa()
function.
由于我的Linux系统I itoa
的功能是不存在的。我用这code这是我从这里找到
Because on my Linux Systems i itoa
function is not there. i am using this code which i found from here
我要在嵌入式设备上也是其中正在使用Linux上运行该功能。
I want to run this function on Embedded devices also which are using Linux.
所以,我找不使用 itoa
。
我硝基甲苯要使用的sprintf
也因为其用途只是印刷品。
I dnt want to use sprintf
also because its uses for just prints.
所以,任何机构请帮我想通了这个问题。
So any body please help me to figured out this problem.
感谢
推荐答案
我就发现这个解决方案。
I found solution regarding this..
我很高兴,我想这是我的预期。
I am Happy to and i want which i expected.
#include <string.h>
#include <stdlib.h>
char *i_to_a(int num);
int main()
{
char *str = i_to_a(4567);
printf("%s",str);
free(str);
str = NULL;
return 0;
}
int no_of_digits(int num)
{
int digit_count = 0;
while(num > 0)
{
digit_count++;
num /= 10;
}
return digit_count;
}
char *i_to_a(int num)
{
char *str;
int digit_count = 0;
if(num < 0)
{
num = -1*num;
digit_count++;
}
digit_count += no_of_digits(num);
str = malloc(sizeof(char)*(digit_count+1));
str[digit_count] = '\0';
while(num > 0)
{
str[digit_count-1] = num%10 + '0';
num = num/10;
digit_count--;
}
if(digit_count == 1)
str[0] = '-';
return str;
}
这篇关于想整型转换为字符串没有itoa功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文