isalpha() function in C++

In this guide, you will learn what is isalpha() function is in C++ programming and how to use it with an example.

1. isalpha() Function Overview

The isalpha() function in C++ checks if the passed character is an alphabetic letter (either uppercase or lowercase). It is housed within the <cctype> header. If the character is alphabetic, the function returns a non-zero value; if not, it returns zero.

Signature:

int isalpha(int ch);

Parameters:

- ch: This character, represented as an int, is to be checked. If the input for ch is of char type, it gets internally converted to an int.

2. Source Code Example

#include <iostream>
#include <cctype>

int main() {
    // Define three characters for testing
    char ch1 = 'A';
    char ch2 = '5';
    char ch3 = '!';

    // Check if ch1 is alphabetic and display the result
    if(isalpha(ch1)) {
        std::cout << ch1 << " is alphabetic." << std::endl;
    } else {
        std::cout << ch1 << " is not alphabetic." << std::endl;
    }

    // Check if ch2 is alphabetic and display the result
    if(isalpha(ch2)) {
        std::cout << ch2 << " is alphabetic." << std::endl;
    } else {
        std::cout << ch2 << " is not alphabetic." << std::endl;
    }

    // Check if ch3 is alphabetic and display the result
    if(isalpha(ch3)) {
        std::cout << ch3 << " is alphabetic." << std::endl;
    } else {
        std::cout << ch3 << " is not alphabetic." << std::endl;
    }

    return 0;
}

Output:

A is alphabetic.
5 is not alphabetic.
! is not alphabetic.

3. Explanation

In the given code, the isalpha() function checks if each of the characters (ch1, ch2, ch3) are alphabetic or not. As expected, the letter 'A' is recognized as alphabetic, but the number '5' and the symbol '!' are not.


Comments