自己实现将整型转化为字符型

来源:互联网 发布:元数据管理工具 编辑:程序博客网 时间:2024/05/21 10:18


#include <stdio.h>void int2str(int n, char *str){    char buf[10] = {0};       //临时数组    int i = 0;                //临时数组buf下标    int j = 0;                //str下标    int len = 0;                  int temp = n < 0 ? -n: n; //取数字n的绝对值    //对负数做处理    if (n < 0)                             {        str[j++] = '-';    }    //将数字倒序存放在临时数组    while (temp)    {        buf[i++] = temp % 10 + '0';        temp /= 10;    }    //完成转换    len = i - 1;    while (len >= 0)    {        str[j++] = buf[len--];    }    str[j] = '\0';}int main(){    int num;    char p[10];    printf("please input an integer:");    scanf("%d", &num);    printf("output:");    int2str(num, p);    printf("%s\n", p);    return 0;}


0 0
原创粉丝点击