整型转字符串(C语言)

整型转字符串实现(C语言)

second60 20180529

#include <stdio.h>
// n <2的32次数,所以最大10位
// n 可能为负数,也可能为正数
void int2str(int n, char *str)
{
    char buf[10] = "";
    int i = 0;
    int len = 0;
    // temp为n的绝对值
    int temp = n<0?-n:n;


    // 如果str为空,直接返回
    if(str == NULL)
    {
     return ;
    }
    //把tmp的每一位的数存入buf
    // 逆序存入,如1234 -> 在buf中为4321
    while(temp)
    {
     buf[i++] = (temp%10) + '0';
     temp = temp / 10;
    }
    //如果是负数多留一位放符串
    len = n<0?++i:i;
    str[i] = 0;
    //反转字符串4321- 转成 -1234
    while(1)
    {
     i--;
     if(buf[len-i-1] == 0)
     {
        break;
     }
     str[i] = buf[len-i-1];
    }
    // 如果是符号,加回去
    if(i==0)
    {
        str[i] = '-';
    }
}


int main()
{
    int nNum=-1234;
    char p[10];
    int2str(nNum, p);
    printf("%s" , p);
    getchar();
    return 0;
}



猜你喜欢

转载自blog.csdn.net/second60/article/details/80490899