免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1220 | 回复: 0
打印 上一主题 下一主题

itoa() and atoi() [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-09-16 20:00 |只看该作者 |倒序浏览

C语言提供了几个标准库函数,可以将任意类型(整型、长整型、浮点型等)的数字转换为字符串。以下是用itoa()函数将整数转 换为字符串的一个例子:
# include
# include
void main (void)
{
int num = 100;
char str[25];
itoa(num, str, 10);
printf("The number 'num' is %d and the string 'str' is %s. \n" ,
num, str);
}
itoa()函数有3个参数:第一个参数是要转换的数字,第二个参数是要写入转换结果的目标字符串,第三个参数是转移数字时所用 的基数。在上例中,转换基数为10。10:十进制;2:二进制...
itoa并不是一个标准的C函数,它是Windows特有的,如果要写跨平台的程序,请用sprintf。
是Windows平台下扩展的,标准库中有sprintf,功能比这个更强,用法跟printf类似:

char str[255];
sprintf(str, "%x", 100); //将100转为16进制表示的字符串。

下列函数可以将整数转换为字符串:
----------------------------------------------------------
函数名 作 用
----------------------------------------------------------
itoa() 将整型值转换为字符串
itoa() 将长整型值转换为字符串
ultoa() 将无符号长整型值转换为字符串
一  atoi     把字符串转换成整型数
例程序:
#include
#include
int atoi (char s[]);
int main(void )
{   
char s[100];
gets(s);
printf("integer=%d\n",atoi(s));
return 0;
}
int atoi (char s[])
{
int i,n,sign;
for(i=0;isspace(s);i++)//跳过空白符
      ;
sign=(s=='-')?-1:1;
if(s=='+'||s==' -')//跳过符号
      i++;
for(n=0;isdigit(s);i++)
      n=10*n+(s-'0');//将数字字符转换成整形数字
return sign *n;
}
      itoa      把一整数转换为字符串
例程序:
#include
#include
void      itoa (int n,char s[]);
//atoi 函数:将s转换为整形数
int main(void )
{   
int n;
char s[100];
printf("Input n:\n");
scanf("%d",&n);
        printf("the string : \n");
        itoa (n,s);
return 0;
}
void itoa (int n,char s[])
{
int i,j,sign;
if((sign=n)0);//删除该数字
if(sign=0;j--)//生成的数字是逆序的,所以要逆序输出
      printf("%c",s[j]);
}


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/93660/showart_2054013.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP