博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
itoa函数及atoi函数
阅读量:4169 次
发布时间:2019-05-26

本文共 1558 字,大约阅读时间需要 5 分钟。

C语言提供了几个标准库函数,可以将任意类型(整型、长整型、浮点型等)的数字转换为字符串。以下是用itoa()函数将整数转 换为字符串的一个例子:

# include <stdio.h>
# include <stdlib.h>
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 <ctype.h>

#include <stdio.h>
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]);i++)//跳过空白符

      ;
sign=(s[i]=='-')?-1:1;
if(s[i]=='+'||s[i]==' -')//跳过符号
      i++;
for(n=0;isdigit(s[i]);i++)
      n=10*n+(s[i]-'0');//将数字字符转换成整形数字
return sign *n;

}

      itoa      把一整数转换为字符串

例程序:

#include <ctype.h>

#include <stdio.h>
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)//记录符号

      n=-n;//使n成为正数
        i=0;
do{
      s[i++]=n%10+'0';//取下一个数字
}while ((n/=10)>0);//删除该数字

if(sign<0)

      s[i++]='-';
s[i]='/0';
for(j=i;j>=0;j--)//生成的数字是逆序的,所以要逆序输出
      printf("%c",s[j]);

}

转载地址:http://adgxi.baihongyu.com/

你可能感兴趣的文章
python编写登录接口
查看>>
python字符串处理常用方法
查看>>
linux echo 向文件中追加信息
查看>>
python列表常见方法
查看>>
python打印列表中指定元素的所有下标(5种方法)
查看>>
python 字典常见方法
查看>>
python字典复制(浅拷贝and深拷贝)
查看>>
python set集合的特点,功能and常见方法
查看>>
python set集合运算(交集,并集,差集,对称差集)
查看>>
python字符串replace()方法
查看>>
python替换文件中的指定内容
查看>>
linux系统下python tab键补全(2步搞定)
查看>>
linux locate 命令使用示例
查看>>
eclipse PyDev 字符集编码设置的3种方法
查看>>
eclipse字体大小设置
查看>>
python __init__.py __name__ __doc__ __file__ argv[0] 浅析
查看>>
Python 命名空间和LEGB规则
查看>>
python 函数的嵌套定义 and 函数的返回值是函数
查看>>
Python 内置函数 locals() 和globals()
查看>>
Python repr() 函数和str() 函数
查看>>