Linux中的itoa功能在哪里?

Ada*_*rce 131 c linux

itoa()是一个非常方便的函数,可以将数字转换为字符串.Linux似乎没有itoa(),是否有相同的功能或我必须使用sprintf(str, "%d", num)

Mat*_*t J 93

编辑:对不起,我应该记得这台机器绝对是非标准的,插入了各种非标准的libc实现用于学术目的;-)

正如itoa()几个有用的评论者所提到的那样,确实是非标准的,最好使用sprintf(target_string,"%d",source_int)或(更好的是,因为缓冲区溢出是安全的)snprintf(target_string, size_of_target_string_in_bytes, "%d", source_int).我知道它不是那么简洁或酷itoa(),但至少你可以写一次,随处运行(tm);-)

这是旧的(编辑过的)答案

你说的是默认gcc libc不包括itoa(),就像其他几个平台一样,因为它在技术上不是标准的一部分.请点击此处获取更多信息.请注意,你必须

#include <stdlib.h>
Run Code Online (Sandbox Code Playgroud)

当然,你已经知道这一点,因为你想使用 itoa()大概使用它在其他平台上后,在Linux上,但...代码(从上面的链接被盗)将如下所示:

/* itoa example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  int i;
  char buffer [33];
  printf ("Enter a number: ");
  scanf ("%d",&i);
  itoa (i,buffer,10);
  printf ("decimal: %s\n",buffer);
  itoa (i,buffer,16);
  printf ("hexadecimal: %s\n",buffer);
  itoa (i,buffer,2);
  printf ("binary: %s\n",buffer);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Enter a number: 1750
decimal: 1750
hexadecimal: 6d6
binary: 11011010110
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!


Jam*_*ill 12

如果你经常调用它,"只使用snprintf"的建议可能很烦人.所以这就是你可能想要的:

const char *my_itoa_buf(char *buf, size_t len, int num)
{
  static char loc_buf[sizeof(int) * CHAR_BITS]; /* not thread safe */

  if (!buf)
  {
    buf = loc_buf;
    len = sizeof(loc_buf);
  }

  if (snprintf(buf, len, "%d", num) == -1)
    return ""; /* or whatever */

  return buf;
}

const char *my_itoa(int num)
{ return my_itoa_buf(NULL, 0, num); }
Run Code Online (Sandbox Code Playgroud)

  • 请记住,这个静态缓冲区不是线程安全的. (17认同)
  • 它不仅仅是非线程安全的,它根本不是很安全: - void some_func(char*a,char*b); some_func(itoa(123),itoa(456)); 小心猜猜功能收到了什么? (14认同)
  • 喜欢评论说:) (8认同)
  • @cat但是这里没有任何const限定的返回类型.`const char*`是一个指向const的非const指针,这很有意义并且是正确的. (3认同)

hac*_*cks 10

itoa不是标准的C函数.你可以实现自己的.它出现在第60页的KernighanRitchie的 C编程语言的第一版中.第二版的C编程语言("K&R2")包含了itoa第64页的以下实现.该书指出了这个实现的几个问题. ,包括它没有正确处理最负数的事实

 /* itoa:  convert n to characters in s */
 void itoa(int n, char s[])
 {
     int i, sign;

     if ((sign = n) < 0)  /* record sign */
         n = -n;          /* make n positive */
     i = 0;
     do {       /* generate digits in reverse order */
         s[i++] = n % 10 + '0';   /* get next digit */
     } while ((n /= 10) > 0);     /* delete it */
     if (sign < 0)
         s[i++] = '-';
     s[i] = '\0';
     reverse(s);
}  
Run Code Online (Sandbox Code Playgroud)

reverse上面使用的函数先前实现了两页:

 #include <string.h>

 /* reverse:  reverse string s in place */
 void reverse(char s[])
 {
     int i, j;
     char c;

     for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
         c = s[i];
         s[i] = s[j];
         s[j] = c;
     }
}  
Run Code Online (Sandbox Code Playgroud)


Mar*_*som 7

编辑:我刚刚发现std::to_string哪个操作与我自己的功能相同.它是在C++ 11中引入的,并且在最新版本的gcc中可用,如果你启用c ++ 0x扩展,至少早在4.5.


不仅itoa缺少gcc,它还不是最方便的功能,因为你需要给它一个缓冲区.我需要一些可以在表达式中使用的东西,所以我想出了这个:

std::string itos(int n)
{
   const int max_size = std::numeric_limits<int>::digits10 + 1 /*sign*/ + 1 /*0-terminator*/;
   char buffer[max_size] = {0};
   sprintf(buffer, "%d", n);
   return std::string(buffer);
}
Run Code Online (Sandbox Code Playgroud)

通常情况下使用它会更安全snprintf,sprintf但缓冲区的尺寸要小心,以免受到膨胀的影响.

查看示例:http://ideone.com/mKmZVE

  • 问题似乎是关于C,它没有'std ::`等东西. (12认同)

小智 6

正如Matt J所写,有itoa,但它不是标准的.如果您使用,您的代码将更加便携snprintf.


mmd*_*bas 5

以下函数分配刚好足够的内存来保留给定数字的字符串表示,然后使用标准sprintf方法将字符串表示写入该区域。

char *itoa(long n)
{
    int len = n==0 ? 1 : floor(log10l(labs(n)))+1;
    if (n<0) len++; // room for negative sign '-'

    char    *buf = calloc(sizeof(char), len+1); // +1 for null
    snprintf(buf, len+1, "%ld", n);
    return   buf;
}
Run Code Online (Sandbox Code Playgroud)

不要忘记在free不需要时增加分配的内存:

char *num_str = itoa(123456789L);
// ... 
free(num_str);
Run Code Online (Sandbox Code Playgroud)

注意当 snprintf 复制 n-1 个字节时,我们必须调用 snprintf(buf, len+1, "%ld", n) (不仅仅是 snprintf(buf, len, "%ld", n))

  • 调用你的函数 `itoa` 不是一个好主意,而是让它的行为与 `itoa` 的常见实现实际上具有不同的行为。这个函数是一个不错的主意,但可以称它为别的 :) 我还建议使用 `snprintf` 来计算缓冲区长度而不是浮点字符串;浮点数可能会出现极端情况不准确的情况。并且 [不要投射 calloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) (4认同)

ric*_*ick 5

Linux 中的 itoa 函数在哪里?

Linux中没有这样的功能。我用这个代码代替。

/*
=============
itoa

Convert integer to string

PARAMS:
- value     A 64-bit number to convert
- str       Destination buffer; should be 66 characters long for radix2, 24 - radix8, 22 - radix10, 18 - radix16.
- radix     Radix must be in range -36 .. 36. Negative values used for signed numbers.
=============
*/

char* itoa (unsigned long long  value,  char str[],  int radix)
{
    char        buf [66];
    char*       dest = buf + sizeof(buf);
    boolean     sign = false;

    if (value == 0) {
        memcpy (str, "0", 2);
        return str;
    }

    if (radix < 0) {
        radix = -radix;
        if ( (long long) value < 0) {
            value = -value;
            sign = true;
        }
    }

    *--dest = '\0';

    switch (radix)
    {
    case 16:
        while (value) {
            * --dest = '0' + (value & 0xF);
            if (*dest > '9') *dest += 'A' - '9' - 1;
            value >>= 4;
        }
        break;
    case 10:
        while (value) {
            *--dest = '0' + (value % 10);
            value /= 10;
        }
        break;

    case 8:
        while (value) {
            *--dest = '0' + (value & 7);
            value >>= 3;
        }
        break;

    case 2:
        while (value) {
            *--dest = '0' + (value & 1);
            value >>= 1;
        }
        break;

    default:            // The slow version, but universal
        while (value) {
            *--dest = '0' + (value % radix);
            if (*dest > '9') *dest += 'A' - '9' - 1;
            value /= radix;
        }
        break;
    }

    if (sign) *--dest = '-';

    memcpy (str, dest, buf +sizeof(buf) - dest);
    return str;
}
Run Code Online (Sandbox Code Playgroud)