字符串转换成整数 c++
注:主函数为测试代码片段;核心代码参考StrToInt函数的定义。
需要考虑的细节:1)“+”,“-”; 2)非法输入:空指针;3)特殊字符;4)溢出。
#include <iostream>
int StrToInt(const char* str);
int main()
{
std::cout << "\"\"" << "\t\t\t" << StrToInt("") << std::endl;
std::cout << "\"1\"\t\t\t" << StrToInt("1") << std::endl;
std::cout << "\"+1\"\t\t\t" << StrToInt("+1") << std::endl;
std::cout << "\"-1\"\t\t\t" << StrToInt("-1") << std::endl;
std::cout << "\"123\"\t\t\t" << StrToInt("123") << std::endl;
std::cout << "\"-123\"\t\t\t" << StrToInt("-123") << std::endl;
std::cout << "\"010\"\t\t\t" << StrToInt("010") << std::endl;
std::cout << "\"+00131204\"\t\t" << StrToInt("+00131204") << std::endl;
std::cout << "\"-01324000\"\t\t" << StrToInt("-01324000") << std::endl;
std::cout << "\"2147483647\"\t\t" << StrToInt("2147483647") << std::endl;
std::cout << "\"-2147483647\"\t\t" << StrToInt("-2147483647") << std::endl;
std::cout << "\"-2147483648\"\t\t" << StrToInt("-2147483648") << std::endl;
std::cout << "\"2147483648\"\t\t" << StrToInt("2147483648") << std::endl;
std::cout << "\"-2147483649\"\t\t" << StrToInt("-2147483649") << std::endl;
std::cout << "\"abc\"" << "\t\t\t" << StrToInt("abc") << std::endl;
std::cout << "\"-abc\"" << "\t\t\t" << StrToInt("-abc") << std::endl;
std::cout << "\"1a\"" << "\t\t\t" << StrToInt("1a") << std::endl;
std::cout << "\"23a8f\"" << "\t\t\t" << StrToInt("23a8f") << std::endl;
std::cout << "\"-3924x8fc\"" << "\t\t" << StrToInt("-3924x8fc") << std::endl;
std::cout << "\" 321\"" << "\t\t\t" << StrToInt(" 321") << std::endl;
std::cout << "\" -321\"" << "\t\t\t" << StrToInt(" -321") << std::endl;
std::cout << "\"123 456\"" << "\t\t" << StrToInt("123 456") << std::endl;
std::cout << "\"123 \"" << "\t\t\t" << StrToInt("123 ") << std::endl;
std::cout << "\" - 321\"" << "\t\t" << StrToInt(" - 321") << std::endl;
std::cout << "\" +4488\"" << "\t\t" << StrToInt(" +4488") << std::endl;
std::cout << "\" + 413\"" << "\t\t" << StrToInt(" + 413") << std::endl;
std::cout << "\" ++c\"" << "\t\t\t" << StrToInt(" ++c") << std::endl;
std::cout << "\"++1\"" << "\t\t\t" << StrToInt("++1") << std::endl;
std::cout << "\"--2\"" << "\t\t\t" << StrToInt("--2") << std::endl;
std::cout << "\" -2\"" << "\t\t\t" << StrToInt(" -2") << std::endl;
return 0;
}
int StrToInt(const char* str)
{
int result = 0;
char signal = '+';
int cur;
// 判断是否为空指针
if ( !str )
return 0;
// 忽略空白
while ( *str == ' ' || *str == '\t' )
str++;
// 判断正负
if ( *str == '+' )
str++;
else if(*str == '-' )
{
signal = '-';
str++;
}
while ( *str != '\0' )
{
if ( *str >= '0' && *str <= '9' )
{
cur = *str - '0';
// 判断是否溢出
if ((signal == '+') && ((result > INT_MAX / 10) || ((result == INT_MAX/10)&&(cur >= INT_MAX % 10))))
return INT_MAX;
if ((signal == '-') && ((result < INT_MIN / 10) || ((-result == INT_MIN / 10) && (-cur <= INT_MIN % 10))) )
return INT_MIN;
result = result * 10 + cur;
str++;
}
else if ( *str == ' ' || *str == '\t' )
str++;
else
return (signal == '+') ? result : -result;
}
return (signal == '+') ? result : -result;
}