How to convert integer to char without C library?

前端 未结 3 756
盖世英雄少女心
盖世英雄少女心 2021-01-28 09:31

In a c programming exercise I am asked to convert an int to char without using the C library.

Any idea how to go about it?

edit: what I mean by int is the built

3条回答
  •  天涯浪人
    2021-01-28 10:00

    If you really want a string:

    #include 
    
    char *tochar(int i, char *p)
    {
        if (i / 10 == 0) {
            // No more digits.
            *p++ = i + '0';
            *p = '\0';
            return p;
        }
    
        p = tochar(i / 10, p);
        *p++ = i % 10 + '0';
        *p = '\0';
        return p;
    }
    
    int main()
    {
        int i = 123456;
        char buffer[100];
        tochar(i, buffer);
        printf("i = %s\n", buffer);
    }
    

提交回复
热议问题