gpt4 book ai didi

c - 在 C 中使用 isdigit() 时遇到困难

转载 作者:行者123 更新时间:2023-11-30 20:50:34 25 4
gpt4 key购买 nike

我一直在尝试将一些 C 语言经验添加到我的 Python 经验中,并从一个基本的加法程序开始。我想做的一件事是检查输入是数字还是字符,如下所示:

#include <stdio.h>
#include <ctype.h>

int main()
{
int n, sum=0,c,value;

printf("Enter the Number of Integers You Want to Add\n");
scanf("%d", &n);

if(isdigit(n))
{
printf("Enter %d Integers\n", n);


for(c=1; c<=n; c++)
{
scanf("%d", &value);

if(isalpha(value))
{
printf("ENTER INTEGER NOT CHARACTER\n");
break;

}
else
{
sum = sum + value;
}
}
printf("Sum of Entered Integers = %d\n",sum);

}

else
{
printf("ENTER INTEGER NOT CHARACTER\n");
break;
}
return 0;
}

最初我尝试使用 isalpha() 进行此操作,程序在添加数字时工作正常,但将字符解释为零,而不是打印“不是整数”语句。然而,现在我重新设计它以使用 isdigit(),它不会将任何输入识别为整数,无论​​它是否是整数。我是不是做错了什么?

最佳答案

当您使用 scanf 读取整数时,您会得到一个整数。 (要读取单个字符,您需要 %c 和一个指向字符的指针)。

当您使用isdigit()时,您需要提供该字符的表示(例如,在 ASCII 中,字符'0'具有表示形式 48,这确实是其整数值)。回顾一下:

isdigit(0)       is false
isdigit(48) is true (for ASCII, ISO8859, UTF-8)
isdigit('0') is true (no matter the character set)
isdigit('0' + n) is true for integers n = 0 ... 9

PS:不测试 scanf 的返回值是自找麻烦......

关于c - 在 C 中使用 isdigit() 时遇到困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43854059/

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