题目:输入一个表示整数的字符串,把该字符串转成整数并输出。例如输入字符串"345",则输出整数345。
思路:例如"345",第一次扫描到3,第二次扫描到4,此时应该让3*10再+4,得到34。继续扫描到5,应该让34*10再+5,得到345。所以可以得出结论:每扫描到一个字符,我们把在之前的得到的数字乘以10再加上当前字符。
边界及特殊情况:
1.整数不只有数字还可能有符号,以'+'或'-'开头。如果第一个字符串为'+'则不做处理,如果为'-',则在最后得到的值变为负数。
2.非法输入。由于输入的是指针,我们需要判断指针是否为空。
3.非法字符。输入的字符串可能含有非数字的字符,碰到非法的字符时,停止转换。
4.溢出问题。因为输入的数字以字符串的形式输入,有可能数字很大导致转换之后的超过能表达的整数而溢出。
#include<iostream>
#include <limits>
using namespace std;
int StrToInt(const char* str)
{
long long num = 0;
if(str != NULL)
{
//判断第一个字符串是否是符号
bool minus = false; //是否是减号,是的话结果应是负的
if (*str == '+')
{
str++; //指向下一个地址
}
else if (*str =='-')
{
str ++;
minus = true;
}
//转换剩下的字符
while(*str != '\0') //判断不是空格
{
if(*str >= '0' && *str <= '9') //处于0~9之间
{
num = num * 10 + (*str - '0');
//判断溢出
if (num > numeric_limits<int> :: max())
{
cout << "溢出";
num = 0;
break;
}
str ++;
}
//如果该字符非数字,即无效字符
else
{
cout << "非法字符";
num = 0;
break;
}
}
if (*str == '\0')
{
if (minus)
num = 0 - num;
}
}
else
{
cout << "空指针异常";
}
return num;
}
// 测试用例
void Test1()
{
int a = StrToInt("12345");
cout << "expected: 12345";
cout << endl;
cout << "result : " << a << endl;
}
void Test2()
{
int a = StrToInt("+12345");
cout << "expected: 12345";
cout << endl;
cout << "result : " << a << endl;
}
void Test3()
{
int a = StrToInt("-12345");
cout << "expected: -12345";
cout << endl;
cout << "result : " << a << endl;
}
void Test4()
{
int a = StrToInt(NULL);
// cout << "expected: 空指针异常";
cout << endl;
cout << "result : " << a << endl;
}
void Test5()
{
int a = StrToInt("12a45");
// cout << "expected: 非法输入";
cout << endl;
cout << "result : " << a << endl;
}
void Test6()
{
int a = StrToInt("1234511111111111111111111");
//cout << "expected: 溢出";
cout << endl;
cout << "result : " << a << endl;
}
int main()
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
}
为什么数字字符与'0'相减可以得到该数字字符的数字值?
这是因为C标准规定0-9这十个数字的字符char值必须是连续递增的,也就是说'1'-'0'等于1是标准保证一定成立的。
顺便说下C标准没有规定字母的char值一定要连续,也就是说标准不保证'B'-'A' == 1一定成立。