C语言 错误:在此范围内未声明`itoa`

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6462938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:59:53  来源:igfitidea点击:

error: `itoa` was not declared in this scope

c

提问by vchitta

I have a sample c file called itoa.cpp as below:

我有一个名为 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;
}

When i compile the above code with the below command:

当我使用以下命令编译上述代码时:

gcc itoa.cpp -o itoa

i am getting this error:

我收到此错误:

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

What is wrong in this code? How to get rid of this?

这段代码有什么问题?如何摆脱这种情况?

回答by Mikola

itoa is not ansi C standard and you should probably avoid it. Here are some roll-your-own implementations if you really want to use it anyway:

itoa 不是 ansi C 标准,您应该避免使用它。如果你真的想使用它,这里有一些你自己的实现:

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

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

If you need in memory string formatting, a better option is to use snprintf. Working from your example:

如果您需要在内存中格式化字符串,更好的选择是使用 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;
}

回答by Jexcy

If you are only interested in base 10, 8 or 16. you can use sprintf

如果您只对基数 10、8 或 16 感兴趣,您可以使用 sprintf

sprintf(buf,"%d",i);

回答by meldo

Look into stdlib.h. Maybe _itoa instead itoa was defined there.

查看 stdlib.h。也许 _itoa 而不是 itoa 是在那里定义的。