Character Functions in C++

C++ contains the functions for working with characters.

C++ provides several functions for testing a character and for converting a character in the <cctype> header file, as shown in Table 4.6. The testing functions test a single character and return true or false. Note that they actually return an int value. A nonzero integer cor­responds to true and zero to false. C++ also provides two functions for converting cases.

LisTing 4.5 CharacterFunctions.cpp

1 #include <iostream>

2 #include <cctype>

3 using namespace std;

4

5 int main()

6 {

7    cout << “Enter a character: “;

8    char ch;

9    cin >> ch;

10

11    cout << “You entered ” << ch << endl;

12

13    if (islower(ch))

14    {

15       cout << “It is a lowercase letter ” << endl;

16       cout << “Its equivalent uppercase letter is ” <<

17       static_cast<char>(toupper(ch)) << endl;

18     }

19    else if (isupper(ch))

20     {

21        cout << “It is an uppercase letter ” << endl;

22        cout << “Its equivalent lowercase letter is ” <<

23        static_cast<char>(tolower(ch)) << endl;

24     }

25    else if (isdigit(ch))

26     {

27        cout << “It is a digit character ” << endl;

28     }

29

30     return 0;

31 }

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *