Skip to main content

Section 9.2 Character Functions

The C++ standard library provides a set of functions for working with characters in the cctype library. Most of these functions are for identifying if a character is an alphabetical character, if it is upper case, if it is lower case, or a digit (numeric), or a whitespace (like a space or tab). They have names like isalpha or islower and you can find a full list at CPPReference.comโ€™s cctype page.
If you look up the function prototypes, you will see they all take and return an integer: int isdigit(int c);. It would make more sense if that function looked like bool isdigit(char c). So what gives? Well, for historical reasons related to the fact that the cctype library is a C++ version of a C library and early versions of C did not have a bool type.
Fortunately, the functions return 0 to indicate false and a non-zero value for true. And those values work as false and true in C++. So if you call isdigit('q') it will return 0, but that counts as false. So you can store it into a bool or use it directly in a test:
Listing 9.2.1.
The other two functions in the cctype library are toupper and tolower. They take an int parameter (that is expected to be an ASCII code). If that ASCII code corresponds to a letter, toupper returns the ASCII code of the upper case version of that letter and tolower returns the lower case code. If the input is not a letter, you just get the same value back. Once again, for historical reasons, the value they return is an int. So to avoid a compiler warning, you must cast the returned value to store it as a char. (Recall from Sectionย 4.5 that casting is how we tell the compiler โ€œI know there might be a problem with doing this conversion, but I am confident it will work. Just do itโ€.)
Listing 9.2.2.

Note 9.2.1.

The cctype library works with regular chars and returns results that make sense for English. If using wide characters (wchar_t) and/or programming fo a language that uses another alphabet, there is a cwctype that works with wide characters and allows you to specify what โ€œlocaleโ€ to use for functions like isalpha. See CPPReference.comโ€™s csctype docs if you are interested in details.
You have attempted of activities on this page.