小智 7

有一个非标准的功能:

char *string = itoa(numberToConvert, 10); // assuming you want a base-10 representation
Run Code Online (Sandbox Code Playgroud)

编辑:似乎你想要一些算法来做到这一点.以下是基础10的方法:

#include <stdio.h>

#define STRINGIFY(x) #x
#define INTMIN_STR STRINGIFY(INT_MIN)

int main() {
    int anInteger = -13765; // or whatever

    if (anInteger == INT_MIN) { // handle corner case
        puts(INTMIN_STR);
        return 0;
    }

    int flag = 0;
    char str[128] = { 0 }; // large enough for an int even on 64-bit
    int i = 126;
    if (anInteger < 0) {
        flag = 1;
        anInteger = -anInteger;
    }

    while (anInteger != 0) { 
        str[i--] = (anInteger % 10) + '0';
        anInteger /= 10;
    }

    if (flag) str[i--] = '-';

    printf("The number was: %s\n", str + i + 1);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)


asv*_*kau 5

这是一个如何工作的例子.给定缓冲区和大小,我们将继续除以10并用数字填充缓冲区.-1如果缓冲区中没有足够的空间,我们将返回.

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;
}
Run Code Online (Sandbox Code Playgroud)


Eri*_* J. 3

您可以在可用的情况下使用itoa。如果它在您的平台上不可用,则可能会对以下实现感兴趣:

https://web.archive.org/web/20130722203238/https://www.student.cs.uwaterloo.ca/~cs350/common/os161-src-html/atoi_8c-source.html

用法:

char *numberAsString = itoa(integerValue); 
Run Code Online (Sandbox Code Playgroud)

更新

根据 R.. 的评论,可能值得修改现有的 itoa 实现以接受来自调用者的结果缓冲区,而不是让 itoa 分配并返回缓冲区。

这样的实现应该接受缓冲区和缓冲区的长度,注意不要写入超过调用者提供的缓冲区的末尾。