|Lessons||Lesson 27: Character Handling Functions|
Sample ProgramLet’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
A sample output of the program is given below.
a character string and then press ENTER: Sixty Five = 65.00
NEXT>>>>>Lesson 28. String Conversion Functions