【发布时间】:2020-05-27 20:56:57
【问题描述】:
我无法理解。当我的函数从 main 中的 char 返回时,随机数。原始 atoi() 返回 -1。我目前使用的是 C11 版本。我从某人那里听说,这是因为 int 溢出,我需要从我的函数中返回 int,但我目前返回的时间很长。如果不是 2147483647,我如何检测 intOverflow
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool mx_isdigit(int c) {
return c >= 48 && c <= 57;
}
bool mx_isspace(char c) {
return (c >= 9 && c <= 13) || c == 32;
}
int mx_atoi(const char *str) {
long num = 0;
int sign = 1;
for (; mx_isspace(*str); str++);
if (*str == '-' || *str == '+') {
sign = *str == '-' ? -sign : sign;
str++;
}
for (; *str; str++) {
if (!mx_isdigit(*str)) {
break;
}
num = (num * 10) + (*str - '0');
}
return sign == -1 ? -num : 0 + num;
}
int main(void) {
char str[100] = "12327123061232712306";
printf("R: %d\n", atoi(str));
printf("M: %d", mx_atoi(str));
}
【问题讨论】:
-
你可以让sign = -sign。就像 5 = -5
-
是的,我想我需要检测溢出。但问题是。如果 char 小于 12327123061232712306 的一位数。原始 atoi() 给我一个随机数而不是 -1。
-
次要注意:使用实际字符而不是数字 ASCII 值是一个非常好的主意;太容易出错了:
return c >= '0' && c <= '9';更好的是使用<ctype.h>宏,它已经有isdigit()和isspace()等。 -
确实,'0'和'9'很容易使用。但是如果我们想检查空白呢? '\n' '\t' ' ' 等等?
-
将
'\n'用于换行,'\t'用于制表符等。但请查看 ctype 宏,因为它们可能已经包含您需要的内容