问题描述:将一个字符串转换成整数
示例:“+123”——>123,"-123"——>-123
分析:
合法输入:“123”,“+123”,“-123”,“098”
非法输入:“a”,“!”,NULL,(超过上下限值的字符串)
逻辑步骤:
- 判断字符串是否为空
- 若为空则显示该字符串为空
- 不为空则继续判断
- 判断首个字符是否为符号
- 判断字符是否在‘0’-‘9’之间
- 若在此区间则为合法输入
- 否则为非法输入
- 判断字符串转换成整数时是否溢出
- 溢出则为非法输入
- 判断到追后一个字符结束(用‘\0’作为结束判断的标志)
代码实现:
#include<iostream>
#include<string>
#include<limits>
using namespace std;
bool input = false;//若数字字符串输入正确则为true
int strtoint(const char *string)
{
input = false;
bool isminus = false;//若数字字符串为负则为true
int result = 0;//用来存放转换结果
const char* digit= string;
if (string == NULL)//若字符串为空
{
std::cerr << "string is NULL" << std::endl;
}
else if (string != NULL)//若字符串不为空
{
if (*digit == '-')
{
isminus = true;
digit++;
}
else if (*digit == '+')
{
digit++;
}
while (*digit != '\0')
{
if (*digit <= '9'&& *digit >= '0')
{
result = result * 10 + (*digit - '0');
if ((result > numeric_limits<int>::max() && !isminus) || (-result < numeric_limits<int>::min() &&isminus))
{
result = 0;
break;
}
digit++;
}
else
{
result = 0;
break;
}
}
if (*digit == '\0')//判断到最后一个字符
{
input = true;
if (isminus)
{
result = 0 - result;
}
}
}
return result;
}
int main()
{
char* str=new char[1024];
cout << "请输入要转换的数字字符串:";
cin >> str;
int result = strtoint(str);
if (input)
{
cout << "转换后的结果为:" << result << endl;
}
else
{
cout << "字符串输入有误,转换失败"<<endl;
}
delete[] str;
system("pause");
}
觉得本文对你有帮助,点个赞噢谢谢