gpt4 book ai didi

检查一个字符是否是数字? (在 C 中)

转载 作者:太空宇宙 更新时间:2023-11-04 00:18:05 24 4
gpt4 key购买 nike

注意我是新手

我以前使用过 isdigit() 函数,但现在我遇到了一个问题:

我需要检查(例如)值为 -46char 是否是数字。 isdigit() 似乎无法识别负数(可能是因为在实际数字之前的那个 -)。

是否有一行简单的代码可以具有与 isdigit() 函数相同的效果,但也能检测负数? (比如 ASCII 表范围之类的)

让我进一步澄清一下:我有一个 char 类型数组:char A[20] 我手动输入每个值(示例):

A[0]= a
A[1]= b
A[2]= -46

现在从这 3 个(忽略剩余的 17 个 - 这只是一个示例)开始,我需要检查其中是否有数字。 -46 是我正在搜索的数字(将其放入另一个数组),所以我的问题是如何检查 -46 是否“是数字”?

最佳答案

诀窍在于 isdigit函数不接受 char 类型的参数.引用标准 ( N1570 7.4p1:

The header <ctype.h> declares several functions useful for classifying and mapping characters. In all cases the argument is an int, the value of which shall be representable as an unsigned char or shall equal the value of the macro EOF. If the argument has any other value, the behavior is undefined.

类型char可以是签名的或未签名的。如果它已签名(这很常见),那么它可以保存负值——并传递除 EOF 以外的负值。 (通常是 -1 )到 isdigit ,或在 <ctype.h> 中声明的任何其他函数, 导致未定义的行为。

解决方案是将参数转换为 unsigned char在将其传递给 isdigit 之前:

char c = -46;
if (isdigit((unsigned char)c) {
puts("It's a digit (?)");
}
else {
puts("It's not a digit");
}

是的,这正如您所想的那样烦人且违反直觉。

关于检查一个字符是否是数字? (在 C 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29321095/

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