6

?なしでCの整数を文字列に変換することは可能です。sprintf

4

5 に答える 5

7

非標準の関数があります:

char *string = itoa(numberToConvert, 10); // assuming you want a base-10 representation

編集:これを行うためのアルゴリズムが必要なようです。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;
}
于 2012-08-05T20:33:34.160 に答える
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;
}
于 2012-08-05T20:48:15.117 に答える
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); 

アップデート

R.. のコメントに基づいて、既存の itoa 実装を変更して、呼び出し元からの結果バッファーを受け入れるようにすることは、itoa にバッファーを割り当てて返すよりも価値があるかもしれません。

このような実装では、バッファーとバッファーの長さの両方を受け入れ、呼び出し元が提供するバッファーの末尾を超えて書き込まないように注意する必要があります。

于 2012-08-05T20:33:43.350 に答える
0
    int i = 24344; /*integer*/
    char *str = itoa(i); 
    /*allocates required memory and 
    then converts integer to string and the address of first byte of memory is returned to str pointer.*/
于 2015-05-16T15:55:45.033 に答える