#include <stdio.h>
#include <string.h>
int OverFlow(int a, int b) {
if (a > 0 && b > 0 && (a + b < 0) || a < 0 && b < 0 && (a + b > 0)) {
return 1;
} else {
return 0;
}
}
int StrToInt(char *str){
int num = 0, len = 0, i = 0, tmp, flag = 1;//1:正数, -1:负数
if (NULL == str) {
printf("str is NULL!\n");
return -1;
}
len = strlen(str);
if (str[0] == '-') {
flag = -1;
i = 1;
} else if (str[0] >= '0' && str[0]) <= '9') {
i = 0;
} else {
num = 0;
printf("input str has special character!\n");
return -1;
}
for(; i < len; i++) {
if(str[i] >= '0' && str[i] <= '9') {
tmp = str[i] - '0';
if (OverFlow(num * 10, tmp)) {
num = 0;
printf("Over the integer range!\n");
return -1;
}
num = num *10 + tmp;
} else {
num = 0;
printf("input str has special character!\n");
return -1;
}
}
return num * flag;
}
int main(void)
{
char buf[20] = "-2147483647";
int result;
result = StrToInt(buf);
if (result == -1) {
printf("failed to convert string to int!\n");
} else {
printf("result = %d\n", result);
}
return 0;
}
字符串转换为整形
最新推荐文章于 2021-10-31 00:00:19 发布