gpt4 book ai didi

c - 对 int 的输入验证

转载 作者:太空宇宙 更新时间:2023-11-04 06:25:04 25 4
gpt4 key购买 nike

我在使用以下代码时遇到问题,当我输入字母时,isdigit 无法检测到它,并且我收到错误消息“未输入任何内容”

    int age;
char buffer[100] = "";
printf("Enter your age: ");
fgets(buffer, 100, stdin);
age = atoi(buffer);
printf("%d\n",age);


if (age == NULL)
{
printf("Nothing entered\n");
}

else if (isdigit(age) == 0)
{
printf("Not a number\n");
}

else if (age <1 || age > 110)
{
printf("Out of range\n");
}

else
{
printf("Thank you\n");
}

最佳答案

atoi 是当您有不可信/可能错误的输入(即几乎总是)时使用的错误函数。

使用strtol() (man page)相反,它允许进行广泛的错误检查。

另外,检查 fgets() 的返回值。

char buf[100];
if (fgets(buf, sizeof buf, stdin)) {
char *end;
errno = 0;
long n = strtol(buf, &end, 10);

// check for errors
if (n == 0 || n == LONG_MIN || n == LONG_MAX) {
if (errno != 0) {
printf("Erroneous input entered\n");
} else {
// process valid input
}
} else {
// process valid input
}
} else {
printf("nothing was entered\n");
}

顺便说一下,将 intNULL(它是一个指针)进行比较是没有意义的。如果这至少不会触发编译器警告(更好的是,硬错误),您需要提高编译器警告级别或更改为现代编译器。

关于c - 对 int 的输入验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28225416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com