数字字符串转整型数据的4种方法

http://blog.csdn.net/acb0y/article/details/6282458

数字字符串转整型数据的4种方法

在项目开发中,我们经常需要把数字字符串(值在整型数据的能够表示的范围内)转换成整型数据,这里我总结C/C++中4种不同转换方式:

1、使用system call调用atoi()来实现。

2、使用system call调用sscanf()来实现。

3、使用C++的字符串流对象来实现。

4、自己手动转换。

Demo代码如下:

  1. /* 
  2.     FileName: main.cpp 
  3.     Author: ACb0y 
  4.     Create Time: 2011年3月27日23:25:38 
  5.     Last Modify Time: 2011年3月27日23:41:31 
  6.  */  
  7. #include <iostream>   
  8. #include <sstream>   
  9. using namespace std;  
  10. int strToDigitOne(char * str)   
  11. {  
  12.     return atoi(str);  
  13. }  
  14. int strToDigitTwo(char * str)  
  15. {  
  16.     int tmp;  
  17.     sscanf(str, "%d", &tmp);  
  18.     return tmp;  
  19. }  
  20. int strToDigitThree(char * str)  
  21. {  
  22.     istringstream in(str);  
  23.     int tmp;  
  24.     in >> tmp;  
  25.     return tmp;  
  26. }  
  27. int strToDigitFour(char * str)   
  28. {  
  29.     int tmp = 0;  
  30.     while (*str)   
  31.     {  
  32.         tmp *= 10;  
  33.         tmp += *str - '0';  
  34.         ++str;  
  35.     }  
  36.     return tmp;  
  37. }  
  38. int main()  
  39. {  
  40.     char str[10] = "009423";  
  41.     printf("digit = %d/n", strToDigitOne(str));  
  42.     printf("digit = %d/n", strToDigitTwo(str));  
  43.     printf("digit = %d/n", strToDigitThree(str));  
  44.     printf("digit = %d/n", strToDigitFour(str));  
  45.     return 0;  
  46. }  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值