思路:
1.‘+’,‘-’问题
2.NULL,‘\0’问题
3.其他字符问题,包括空格、tab
4.越界溢出问题
5.数字前面几位是0
#include<iostream> using namespace std; #include<stdlib.h> enum Status{ KValid = 0, KInvalid }; //KVlid-合法 KInvalid-非法 int g_nStatus = KValid; //在最后得到结果时,判断是合法的0,还是非法的非0 int StrToInt(const char* str) { long long StrToIntCore(const char *digit, bool minus); g_nStatus = KInvalid; long long num = 0; if (str != NULL&&*str != ‘\0‘)//判空,‘\0‘ { bool minus = false; //符号 默认为负 if (*str == ‘+‘) { str++; } else if (*str == ‘-‘) { str++; minus = true; } if (*str != ‘\0‘) { num = StrToIntCore(str, minus); } } return (int)num; } long long StrToIntCore(const char *digit, bool minus) { long long num = 0; while (*digit != ‘\0‘) { if (isdigit(*digit)) //while(*digit >= ‘0‘&&*digit <= ‘9‘) { int flag = minus ? -1 : 1; num = num * 10 + flag*(*digit - ‘0‘); if ((!minus&&num > 0x7fffffff) || (minus&&num < (signed int)0x80000000)) { num = 0; break; } digit++; } else { num++; break; } } if (*digit == ‘\0‘) { g_nStatus = KValid; } return num; } int main() { char str[] = "-12345"; char str1[] = "-012345"; char str2[] = "012345"; char str3[] = "--12345"; cout << StrToInt(str) << endl; cout << g_nStatus << endl; cout << StrToInt(str1) << endl; cout << g_nStatus << endl; cout << StrToInt(str2) << endl; cout << g_nStatus << endl; cout << StrToInt(str3) << endl; cout << g_nStatus << endl; system("pause"); return 0; }
时间: 2024-10-08 08:16:05