gpt4 book ai didi

c - 错误 : `itoa` was not declared in this scope

转载 作者:太空狗 更新时间:2023-10-29 16:26:51 26 4
gpt4 key购买 nike

我有一个名为 itoa.cpp 的示例 c 文件,如下所示:

#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);
return 0;
}

当我用下面的命令编译上面的代码时:

gcc itoa.cpp -o itoa

我收到这个错误:

[root@inhyuvelite1 u02]# gcc itoa.cpp -o itoaitoa.cpp: In function "int main()":itoa.cpp:10: error: "itoa" was not declared in this scope

这段代码有什么问题?如何摆脱这个?

最佳答案

itoa 不是 ANSI C 标准,您应该避免使用它。如果您无论如何都想使用它,这里有一些您自己的实现:

http://www.strudel.org.uk/itoa/

如果您需要在内存中格式化字符串,更好的选择是使用 snprintf。从你的例子开始:

#include <stdio.h>
#include <stdlib.h>

int main ()
{
int i;
char buffer [33];
printf ("Enter a number: ");
scanf ("%d",&i);
snprintf(buffer, sizeof(buffer), "%d", i);
printf ("decimal: %s\n",buffer);
return 0;
}

关于c - 错误 : `itoa` was not declared in this scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6462938/

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