【发布时间】:2016-07-19 10:24:40
【问题描述】:
这是我为了检查输入是否为正整数而写的
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int isInt(char num[3]) {
int l = strlen(num);
int x;
for ( x = 0; x < l; x++) {
if ( ! isdigit(num[x]) )
return 0;
}
return 1;
}
int main(void) {
int i;
char str[3];
printf("Enter a positive integer: ");
scanf("%s", str);
if ( isInt(str) == 1 ) {
i = atoi(str);
printf("%d \n", i);
} else {
printf("This is not a positive integer! \n");
}
return 0;
}
我发现了一些意想不到的行为,尽管程序似乎可以运行:
我是否
#include <ctype.h>没有区别。isdigit()函数在没有库的情况下如何工作? (我在 ubuntu 14.04 上使用 gcc 4.9.3)如果我将
str强制为长度为3 的字符串,那么当我运行./a.out时,它如何正确检查并打印大于999 的数字?如果我输入 5678 不应该str只保存 567?或者它可能会保存前 2^3 位数字?我很困惑如果我想检查一个字符串是否为正整数,但数字可能很大,
str应该有多大?有没有办法让它按需要变大?
【问题讨论】:
-
最好每次问一个问题。而且您的大多数问题之前都有重复,请先搜索该网站。
-
越界写入,未定义行为。
-
代码构建对您不利,因为超出范围会给出工作结果。
-
您可以使用动态内存分配,并根据需要使用
realloc()。 -
int l = strlen(num);错误应该是size_t l = strlen(num);也应该是scanf("%s", str);应该是scanf("%2s", str);
标签: c string integer type-conversion