Linux中的itoa函数在哪里? [英] Where is the itoa function in Linux?

查看:34
本文介绍了Linux中的itoa函数在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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() 是正确的,就像其他几个平台一样,因为它在技术上不是标准的一部分.请参阅此处了解更多信息.请注意,您必须

#include 

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

示例

/* itoa 示例 */#include #include int主(){国际我;字符缓冲区[33];printf("请输入一个数字:");scanf ("%d",&i);itoa (i,buffer,10);printf ("十进制:%s
",buffer);itoa (i,buffer,16);printf ("十六进制:%s
",buffer);itoa (i,buffer,2);printf ("二进制:%s
",buffer);返回0;}

输出:

<块引用>

输入一个数字:1750十进制:1750十六进制:6d6二进制:11011010110

希望这有帮助!

itoa() is a really handy function to convert a number to a string. Linux does not seem to have itoa(), is there an equivalent function or do I have to use sprintf(str, "%d", num)?

解决方案

EDIT: Sorry, I should have remembered that this machine is decidedly non-standard, having plugged in various non-standard libc implementations for academic purposes ;-)

As itoa() is indeed non-standard, as mentioned by several helpful commenters, it is best to use sprintf(target_string,"%d",source_int) or (better yet, because it's safe from buffer overflows) snprintf(target_string, size_of_target_string_in_bytes, "%d", source_int). I know it's not quite as concise or cool as itoa(), but at least you can Write Once, Run Everywhere (tm) ;-)

Here's the old (edited) answer

You are correct in stating that the default gcc libc does not include itoa(), like several other platforms, due to it not technically being a part of the standard. See here for a little more info. Note that you have to

#include <stdlib.h>

Of course you already know this, because you wanted to use itoa() on Linux after presumably using it on another platform, but... the code (stolen from the link above) would look like:

Example

/* 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
",buffer);
  itoa (i,buffer,16);
  printf ("hexadecimal: %s
",buffer);
  itoa (i,buffer,2);
  printf ("binary: %s
",buffer);
  return 0;
}

Output:

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

Hope this helps!

这篇关于Linux中的itoa函数在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆