博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C语言数字与字符串转换 atoi()函数、itoa()函数、sprintf()函数
阅读量:6994 次
发布时间:2019-06-27

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

在编程中经常需要用到数字与字符串的转换,下面就总结一下。

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 }

  

转载于:https://www.cnblogs.com/xudong-bupt/p/3479350.html

你可能感兴趣的文章
node爬虫
查看>>
【转】在写一个iOS应用之前必须做的7件事(附相关资源)
查看>>
[转]什么是线程安全
查看>>
STlink下载和打断点Debug调试小结
查看>>
MySQL数据库与JDBC编程(一)
查看>>
移动端fixed后 横竖屏切换时上部或下部出现空隙问题
查看>>
poj 3122 Pie (二分)
查看>>
在面试中如何展示虚拟机和内存调优技能
查看>>
C++命名空间学习笔记
查看>>
购物商城Web开发第五天
查看>>
剑指Offer第36题—Java版
查看>>
txt 简单操作
查看>>
jquery $(document).ready() 与window.onload的区别
查看>>
解决Android中,禁止ScrollView内的控件改变之后自动滚动
查看>>
软件测试2019:第七次作业—— 用户体验测试
查看>>
.NET Winform 让程序以兼容模式运行
查看>>
Maven的配置文件pom.xml
查看>>
Flask
查看>>
Pycharm中实现多个项目共存的方式
查看>>
【转】一步一步学Linq to sql(三):增删改
查看>>