HowToProgramC : Lesson 27

Back Home Next

Application of Character Handling Functions

Sample Program

Let’s consider the following example to further demonstrate the use of the functions of ctype.h. Suppose, we write a program which prompts the user to enter a string. Then the string entered is checked to count different types of characters (digit, upper and lowercase letters, white space etc). We keep a counter for each category of character entered. When the user ends the input, the number of characters entered in different types will be displayed. In this example we are using a function getchar(), instead of cin to get the input. This function is defined in header file as stdio.h. While carrying out character manipulation, we use the getchar() function. This function reads a single character from the input buffer or keyboard. This function can get the new line character ‘\n’ (the ENTER key) so we run the loop for input until user presses the ENTER key. As soon as the getchar() gets the ENTER key pressed (i.e. new line character ‘\n’), the loop is terminated. We know that, every C statement returns a value. When we use an assignment statement ( as used in our program c = getchar()), the value assigned to the left hand side variable is the value of the statement too. Thus, the statement (c = getchar()) returns the value that is assigned to char c. Afterwards, this value is compared with the new line character ‘\n’. If it is not equal inside the loop, we apply thetests on c to check whether it is uppercase letter, lowercase letter or a digit etc. In this
program, the whole string entered by the user is manipulated character by character.

Following is the code of this program.

// Example: analysis of text using <ctype.h> library
#include <iostream.h>
#include <stdio.h>
#include <ctype.h>
char c;
int i = 0, lc = 0, uc = 0, dig = 0, ws = 0, pun = 0, oth = 0;
cout << "Please enter a character string and then press ENTER: ";
// Analyse text as it is input:
while ((c = getchar()) != '\n')
if (islower(c))
else if (isupper(c))
else if (isdigit(c))
else if (isspace(c))
else if (ispunct(c))
// display the counts of different types of characters
cout << "You typed:"<< endl;
cout<< "lower case letters = "<< lc<< endl;
cout << "upper case letters = " << uc <<endl;
cout<< "digits = " << dig << endl;
cout<< "white space = "<< ws << endl;
cout<< "punctuation = "<< pun<< endl;
cout<< "others = "<< oth;

A sample output of the program is given below.

Please enter a character string and then press ENTER: Sixty Five = 65.00
You typed:
lower case letters = 7
upper case letters = 2
digits = 4
white space = 3
punctuation = 2
others = 0

Back Home Next

© All rights Reserved.