http://blog.csdn.net/acb0y/article/details/6282458
数字字符串转整型数据的4种方法
在项目开发中,我们经常需要把数字字符串(值在整型数据的能够表示的范围内)转换成整型数据,这里我总结C/C++中4种不同转换方式:
1、使用system call调用atoi()来实现。
2、使用system call调用sscanf()来实现。
3、使用C++的字符串流对象来实现。
4、自己手动转换。
Demo代码如下:
- /*
- FileName: main.cpp
- Author: ACb0y
- Create Time: 2011年3月27日23:25:38
- Last Modify Time: 2011年3月27日23:41:31
- */
- #include <iostream>
- #include <sstream>
- using namespace std;
- int strToDigitOne(char * str)
- {
- return atoi(str);
- }
- int strToDigitTwo(char * str)
- {
- int tmp;
- sscanf(str, "%d", &tmp);
- return tmp;
- }
- int strToDigitThree(char * str)
- {
- istringstream in(str);
- int tmp;
- in >> tmp;
- return tmp;
- }
- int strToDigitFour(char * str)
- {
- int tmp = 0;
- while (*str)
- {
- tmp *= 10;
- tmp += *str - '0';
- ++str;
- }
- return tmp;
- }
- int main()
- {
- char str[10] = "009423";
- printf("digit = %d/n", strToDigitOne(str));
- printf("digit = %d/n", strToDigitTwo(str));
- printf("digit = %d/n", strToDigitThree(str));
- printf("digit = %d/n", strToDigitFour(str));
- return 0;
- }