您好,登錄后才能下訂單哦!
思路:
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; }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。