Print an int in C without Printf or any functions

后端 未结 3 1309
闹比i
闹比i 2021-01-19 03:37

I have an assignment where I need to print an integer in C without using printf, putchar, etc. No header files allowed to be included. No function calls except for anything

3条回答
  •  长情又很酷
    2021-01-19 04:37

    You can convert an int to char * , char * and display this char* :

    char        *put_int(int nb)
    {
     char       *str;
    
     str = malloc(sizeof(char) * 4);
     if (str == NULL)
       return (0);
     str[0] = (nb / 100) + '0';
     str[1] = ((nb - ((nb / 100 * 100 )) / 10) + '0');
     str[2] = ((nb % 10) + '0');
     return (str);
    }
    
    void        put_str(char *str)
    {
     while (*str)
       write(1, str++,1);
    }
    
    int main(void)
    {
     put_str(put_int(42));
     return (0);
    }
    

提交回复
热议问题