开发者

What is the simplest way of using isdigit() and isalpha() commands?

I need a brief explanation on how the two commands isdigit() and isalpha() work. Of course, I read online sources before asking the question, but I tried them and couldn't get them to work. What is the s开发者_运维知识库implest way of using them?

I know it gives back a value, so I'm assuming I can use it like this:

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

Is that correct? Can I use this for any type of character? And can I compare it with a float number or array?

Suppose, I want to scanf a text file that has numbers and letter and determine what I'm scanning. Can these two commands be used in this context?


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.


They are not "commands", they are functions. Functions accept arguments and return values.

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

This is the signature for the isdigit function: it indicates that it will accept an int value (or something that can be cast to int, like a char), and will return an int. You cannot, therefore, pass it an array (though you can call it on every member of an int[]).

The signature for isalpha is identical (except for the name, obviously).

The documentation says the following:

Description: The function isalpha() returns non-zero if its argument is a letter of the alphabet. Otherwise, zero is returned.

This means your comparison will not be correct for all implementations. Better to do something like:

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.


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"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜