Get number into a string C without stdio

前端 未结 5 1842
忘掉有多难
忘掉有多难 2021-01-21 10:41

I want to know how to get number to string without standard C or C++ functions, for example:

char str[20];
int num = 1234;
// How to convert that number to strin         


        
5条回答
  •  忘掉有多难
    2021-01-21 11:26

    An "after accepted answer" that works for all int including INT_MIN.

    static char *intTostring_helper(int i, char *s) {
      if (i < -9) {
        s = intTostring_helper(i/10, s);
      }
      *s++ = (-(i%10)) + '0' ;
      return s;
    }
    
    char *intTostring(int i, char *dest) {
      char *s = dest;
      if (i < 0) {  // If non 2s compliment, change to some IsSignBitSet() function.
        *s++ = '-';
      }
      else {
        i = -i;
      }
      s = intTostring_helper(i, s);
      *s = '\0';
      return dest;
    }
    

提交回复
热议问题