Converting integer to string in C without sprintf

后端 未结 5 2161
一向
一向 2020-12-17 03:56

It is possible to convert integer to string in C without sprintf?

5条回答
  •  旧时难觅i
    2020-12-17 04:30

    Here's an example of how it might work. Given a buffer and a size, we'll keep dividing by 10 and fill the buffer with digits. We'll return -1 if there is not enough space in the buffer.

    int
    integer_to_string(char *buf, size_t bufsize, int n)
    {
       char *start;
    
       // Handle negative numbers.
       //
       if (n < 0)
       {
          if (!bufsize)
             return -1;
    
          *buf++ = '-';
          bufsize--;
       }
    
       // Remember the start of the string...  This will come into play
       // at the end.
       //
       start = buf;
    
       do
       {
          // Handle the current digit.
          //
          int digit;
          if (!bufsize)
             return -1;
          digit = n % 10;
          if (digit < 0)
             digit *= -1;
          *buf++ = digit + '0';
          bufsize--;
          n /= 10;
       } while (n);
    
       // Terminate the string.
       //
       if (!bufsize)
          return -1;
       *buf = 0;
    
       // We wrote the string backwards, i.e. with least significant digits first.
       // Now reverse the string.
       //
       --buf;
       while (start < buf)
       {
          char a = *start;
          *start = *buf;
          *buf = a;
          ++start;
          --buf;
       }
    
       return 0;
    }
    

提交回复
热议问题