2

我需要简要解释这两个命令的isdigit()工作isalpha()原理。当然,我在提出问题之前阅读了在线资源,但我尝试了它们并且无法让它们工作。使用它们的最简单方法是什么?

我知道它会返回一个值,所以我假设我可以像这样使用它:

if(isdigit(someinput)==1)
 return -1;

那是对的吗?我可以将它用于任何类型的角色吗?我可以将它与浮点数或数组进行比较吗?

假设,我想扫描一个包含数字和字母的文本文件,并确定我正在扫描什么。这两个命令可以在这种情况下使用吗?

4

3 回答 3

2

You do not normally want to compare the return value, just treat it as a Boolean:

if (isalpha(someinput))
    do_whatever();

If you insist on doing a comparison, it needs to be !=0, but it's entirely redundant and pointless.

You use it on characters that have been read from input, which are not (at that point) floats or anything, just groups of characters. In the case of a float, some of those will be digits, but many will also include decimal points (which aren't digits) and possibly an occasional e, + or - as well.

Also note that you normally need to cast the input to unsigned char before calling any of the is* functions. Many character sets will treat some characters as negative when they're viewed as signed char, and passing a negative value to any of these gives undefined behavior.

于 2010-05-11T20:36:17.257 回答
1

它们不是“命令”,而是函数。函数接受参数和返回值。

#include <ctype.h>
int isdigit( int ch );

这是isdigit函数的签名:它表明它将接受一个int值(或可以转换为的东西int,如 a char),并将返回一个int. 因此,您不能将数组传递给它(尽管您可以在 的每个成员上调用它int[])。

的签名isalpha是相同的(显然除了名称)。

该文档说明了以下内容:

说明:如果函数 isalpha() 的参数是字母表中的字母,则函数返回非零值。否则,返回零。

这意味着您的比较不会对所有实现都正确。最好做类似的事情:

if (isdigit(someinput)) {
 return -1;
}

In C, 0 will evaluate to false in a boolean expression, and all non-zero values evaluate to true. So this check will cover implementations of isdigit that return -1, 5, whatever.

If you want to apply these to values in a text file, you must read the text one character at a time and pass the characters you receive to those methods.

于 2010-05-11T20:35:45.010 回答
0

You can use it for any char type! (actually it's int, I don't know whether this is for compatibilty reasons or whatnot, but the most common usage is for characters)

It will determine whether for example '5' is a digit or an alphanumerical (part of the alphabet). And yes, your usage is correct if someInput is of type "char"

于 2010-05-11T20:35:56.397 回答