[英]I'm trying to make a function that converts integer to string which is not returning the string. How can I solve this?
我正在嘗試使用此代碼將整數轉換為字符串它正在打印值但沒有向調用 function 返回任何內容
char* itoa(int num, int num_len)
{
char str[num_len+2];
int i;
//if the num is 0
if(num == 0)
strcpy(str, "0");
//if the num is negetive then we append a '-' sign at the beginning
//and put '\0' at (num_len+1)th position
else if(num < 0)
{
num *= -1;
str[num_len+1] = '\0';
str[0] = '-';
i = num_len+1;
}
//we put '\0' (num_len)th position i.e before the last position
else
{
str[num_len] = '\0';
i = num_len;
}
for(;num>0;num/=10,i--)
{
str[i] = num%10 + '0';
printf("%c ",str[i]);//for debugging
}
return str;
}
我只是忘記了那個規則。 非常感謝您
char* itoa(int num, int num_len,char* str)
{
int i;
str = (char*)malloc((num_len + 2)*sizeof(char));
if(num == 0)
strcpy(str, "0");
else if(num < 0)
{
num *= -1;
str[num_len+1] = '\0';
str[0] = '-';
i = num_len;
}
else
{
str[num_len] = '\0';
i = num_len-1;
}
for(;num>0;num/=10,i--)
{
str[i] = num%10 + '0';
printf("%c ",str[i]);
}
return str;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.