user3287789
user3287789

Reputation: 121

Easy way to differentiate between number and letter in C

I'm currently reading in a file, and storing that file into a cstring. I'm using strtok to parse it out for the first few strings i'm interested in. After that, the substrings could be numbers (500,150,30) or character combinations( P(4),(K(5)). Is there an easy method in the string library to differentiate between numbers and letters? \

Thanks for the answers guys!

Upvotes: 1

Views: 2939

Answers (3)

zmo
zmo

Reputation: 24812

well, if you're reading a stream of bytes and want to differentiate between numbers and letters the following can be done:

// returns true if given char is a character, false otherwise
bool is_letter(char c) {
    return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}

which is easy enough to implement where it is needed. If you really want a library function, you can still use isalpha() or isdigit() from ctype.h, which basically should do the same thing.

N.B.: you might want to choose between bool or unsigned short. I won't enter into that debate.

Upvotes: 1

user2203117
user2203117

Reputation:

If you are sure that there are no other symbols (@#$%^%&*^) you can use the isalpha() function.

Usage:

   isalpha(p);// returns true if its alphabetic and false otherwise.

Also note that you should include ctype.h.

Upvotes: 1

user3125367
user3125367

Reputation: 3000

You probably look for isalpha and isdigit library functions.

Upvotes: 1

Related Questions