isdigit() function in C++

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

1. isdigit() Function Overview

The isdigit() function is part of the C++ <cctype> library. This function checks if the passed character is a decimal digit character (0-9).

Signature:

int isdigit(int ch);

Parameters:

- ch: The character to be checked. Although it's an int, it essentially represents the ASCII value of the character.

2. Source Code Example

#include <iostream>
#include <cctype>

int main() {
    char ch1 = '5';
    char ch2 = 'A';

    if(isdigit(ch1)) {
        std::cout << "ch1 is a decimal digit character." << std::endl;
    } else {
        std::cout << "ch1 is not a decimal digit character." << std::endl;
    }

    if(isdigit(ch2)) {
        std::cout << "ch2 is a decimal digit character." << std::endl;
    } else {
        std::cout << "ch2 is not a decimal digit character." << std::endl;
    }

    return 0;
}

Output:

ch1 is a decimal digit character.
ch2 is not a decimal digit character.

3. Explanation

In the given example, the isdigit() function is used to determine whether a character is a decimal digit or not. The character '5' is a decimal digit, so for ch1, the function returns true. However, ch2 which holds the character 'A' isn't a decimal digit, hence for ch2, it returns false.


Comments