gpt4 book ai didi

c - Linux 中的 itoa 函数在哪里?

转载 作者:行者123 更新时间:2023-11-30 17:38:41 25 4
gpt4 key购买 nike

itoa() 是将数字转换为字符串的非常方便的函数。 Linux 似乎没有 itoa(),是否有等效的函数或者我必须使用 sprintf(str, "%d", num)

最佳答案

编辑:抱歉,我应该记得这台机器绝对是非标准的,出于学术目的插入了各种非标准 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(),就像其他几个平台一样,因为它在技术上不是标准的一部分。请参阅here了解更多信息。请注意,您必须

#include <stdlib.h>

当然,您已经知道这一点,因为您想在 Linux 上使用 itoa()(大概是在另一个平台上使用它),但是...代码(被盗)从上面的链接)看起来像:

示例

/* 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;
}

输出:

Enter a number: 1750
decimal: 1750
hexadecimal: 6d6
binary: 11011010110

关于c - Linux 中的 itoa 函数在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22060091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com