问题描述:输入一个表示整数的字符串,把该字符串转换成整数并输出。例如输入字符串"345",则输出整数345。
思路:转换的过程比较简单,每次读入一个字符,将之前保存的值乘以10,然后再加上这个字符表示的数字。这是正常情况。这个问题主要是考察各种不正常情况的处理。假设函数的声明为 int StrToInt(const char *str);
(1)输入的字符串指针为空;
(2)数字前面有正负号的处理;
(3)字符串表示的数字超过了32位整数能表示的范围,即溢出处理;
(4)输入了非法字符,即除了数字及正负号的其他字符;
(5)以字符' 0 '开始的串,' 0 '后面还跟了其他字符,也是非法的。
如果能很好的处理这些情况,那么程序的健壮性大大增强。其中有两种情况处理起来有点麻烦,第一,如何处理溢出,我们可以使用std::numeric_limits<int>::max(),可以定义一个long long的变量,然后与这个最大值相比,从而判断是否溢出了。第二。由于返回值为一个整型数,那么如果转换失败,返回什么呢?如果是'0 ' ,那么就无法区分正常输入"0"的情况。两种方案,修改函数声明,通过返回值表明转换的成功与否,或者定义一个全局变量,用来保存转换的成功与否。参考代码中使用了第二种方案。
参考代码:先给出的是std::numeric_limits<int>::max()的用法。
- #include <iostream>
- #include <limits> //需包含这个头文件
- using namespace std;
- int main() {
- cout << "The maximum value for type float is: "
- << numeric_limits<float>::max( )
- << endl;
- cout << "The maximum value for type double is: "
- << numeric_limits<double>::max( )
- << endl;
- cout << "The maximum value for type int is: "
- << numeric_limits<int>::max( )
- << endl;
- cout << "The maximum value for type short int is: "
- << numeric_limits<short int>::max( )
- << endl;
- }
- bool strToIntOK; //全局的变量
- int StrToInt(const char *str)
- {
- strToIntOK = false;
- if(str == NULL) //空指针
- return 0;
- if(str[0] == '0' && str[1] != '\0') //以'0'开始但不是"0" 这条其实可以忽略
- return 0;
- unsigned i = 0;
- bool minus = false; //负数标记
- if(str[i] == '-' || str[i] == '+') //判断是不是以正负号开始
- {
- minus = (str[i] == '-')? true: false;
- i++;
- }
- long long result = 0; //转换的结果
- while(str[i] != '\0')
- {
- char c = str[i++];
- if(c >= '0' && c <='9')
- {
- result = result * 10 + (c - '0');
- if(minus) //负溢出
- {
- if(result - 1 > numeric_limits<int>::max())
- return 0;
- }
- else //正溢出
- {
- if(result > numeric_limits<int>::max())
- return 0;
- }
- }
- else
- {
- return 0;
- }
- }
- strToIntOK = true;
- //结果返回 需强制转换一下
- return minus? (int)(-result):(int)result;