ANSI C, integer to string without variadic functions

强颜欢笑 提交于 2019-12-05 17:41:04

This is from K&R:

void itoa(int n, char s[])
{
    int i, sign;

    if ((sign = n) < 0)  /* record sign */
        n = -n;          /* make n positive */
    i = 0;
    do {       /* generate digits in reverse order */
        s[i++] = n % 10 + '0';   /* get next digit */
    } while ((n /= 10) > 0);     /* delete it */
    if (sign < 0)
        s[i++] = '-';
    s[i] = '\0';
    reverse(s);
} 

reverse() just reverses a string.

NullAndVoid

Just for the sake of completeness and as a reference for others that may stumble upon the subject, I added this link to a recursive implementation of itoa itoa recursively which I like because of its simple beauty, but can't use for my target system.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!