C语言数字与字符串转换 atoi()函数、itoa()函数、sprintf()函数

在编程中经常需要用到数字与字符串的转换,下面就总结一下。1.atoi()  C/C++标准库函数,用于字符串到整数的转换。  函数原型:int atoi (const char * str);1 #include 2 #include 3 int main ()4 {5 char *numchars="1234";6 int num=atoi(numchars);7 printf("%d\n",num);8 return 0;9 }  另外C/C++还提供的标准库函数有:  (1)long int atol ( const char * str );    (2)double atof (const char* str);2.itoa()  不是C/C++标准库函数,用于整数到字符串的转换。  函数原型:char *itoa(int value, char *string, int radix); 1 #include 2 #include 3 int main () 4 { 5 int num=1234; 6 int radix=8; 7 char res[20]; 8 itoa(num,res,radix); 9 printf("%d(10)=%s(%d)\n",num,res,radix); //输出:1234(10)=2322(8)10 return 0;11 }3.sprintf()  C/C++标准库函数,可以用于整数到字符串的转换。  sprintf:Write formatted data to string。  sprintf作用是将printf的输出结果保存在字符串数组中。 1 #include 2 #include 3 int main () 4 { 5 int num=1234; 6 char res[20]; 7 sprintf(res,"%0o",num); 8 printf("%s\n",res); //8进制输出:2322 9 10 sprintf(res,"%0x",num);11 printf("%s\n",res); //16进制输出:4d212 return 0;13 }  分类: C
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值