标签:
参考自:http://taop.marchtea.com/01.03.html
下面是我实现的代码,如有不妥之处,望指正,谢谢!
#include <stdio.h> const int INT_MAX = (int)((unsigned)~0 >> 1); const int INT_MIN = -(int)((unsigned)~0 >> 1) - 1; int StrToInt(const char *str) { if (str == NULL) { printf("The string is null!"); exit(1); } int num = 0; if (str[0] != ‘-‘ && str[0] == ‘+‘ || (str[0] -‘0‘ <=9 && str[0] - ‘0‘ >=0)) { for (int i = 0; str[i] != ‘\0‘; ++i) { if (str[i] - ‘0‘ <= 9 && str[i] - ‘0‘ >= 0) { if (num > INT_MAX / 10 || (num == INT_MAX / 10 && (str[i] - ‘0‘) > INT_MAX % 10)) { num = INT_MAX; break; } else{ num *= 10; num += (str[i] - ‘0‘); } } else{ printf("Having a wrong with input!"); exit(1); } } } else if (str[0] == ‘-‘){ for (int i = 1; str[i] != ‘\0‘; ++i) { if (str[i] - ‘0‘ <= 9 && str[i] - ‘0‘ >= 0) { if (num < INT_MIN / 10 || (num == INT_MIN / 10 && (str[i] - ‘0‘) > -(INT_MIN % 10))) { num = INT_MIN; break; } else{ num *= 10; num -= (str[i] - ‘0‘); } } else{ printf("Having a wrong with input!"); exit(1); } } } else{ printf("It‘s wrong!"); exit(1); } return num; }
标签:
原文地址:http://www.cnblogs.com/mingbujian/p/5098344.html