Skip to main content

ctype.h

The ctype.h header file defines a series of prototypes for character handling functions.

Character test functions

These functions are used to determine whether a character is of a certain type.

  • isalnum(): whether it is an alphanumeric
  • isalpha(): whether or not it is an alphabet
  • isdigit(): whether or not it is a number
  • isxdigit(): whether or not it is a hexadecimal numeric character
  • islower(): whether it is a lowercase letter
  • isupper(): whether it is an uppercase letter
  • isblank(): whether it is a standard blank character (containing spaces, horizontal tabs or line breaks)
  • isspace(): whether blank characters (spaces, line feeds, page breaks, carriage returns, vertical tabs, horizontal tabs, etc.)
  • iscntrl(): whether or not it is a control character, e.g. Ctrl + B
  • isprint(): whether or not it is a printable character
  • isgraph(): whether to be any printable character other than a space
  • ispunct(): whether to be punctuation (printable characters other than spaces, letters, numbers)

They accept a character to be tested as an argument. Note that the argument type is int, not char, as they allow EOF as an argument.

If the argument character is of the specified type, a non-zero integer is returned (usually 1, indicating true), otherwise 0 (indicating pseudo) is returned.

Here is an example where the user enters a character and the program determines if it is an alphabet.

#include <stdio.h>
#include <ctype.h>

int main(void) {
char ch = getchar();

if (isalpha(ch))
printf("it is an alpha character.\n");
else
printf("it is not an alpha character.\n");

return 0;
}

Character mapping functions

This class of functions returns some equivalent form of character, and there are two main functions.

  • tolower(): if the argument is an uppercase character, returns the lowercase character, otherwise returns the original argument.
  • `toupper(): if the argument is a lowercase character, returns the uppercase character, otherwise returns the original argument.
// convert characters to uppercase
ch = toupper(ch);

Note that these two functions do not change the original characters.