The isdigit() function in C++ checks whether a given character is a digit or not. Let's take a look at an example:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
char c = '5';
if (isdigit(c))
cout << c << " is a Digit";
else
cout << c << " is not a Digit";
return 0;
}
Explanation: The isdigit() function returns a non-zero value if the character is a digit. Since c is a digit, it returns a non-zero (true) value.
This article provides an overview of the syntax, working and use cases of the isdigit() function in C++.
Syntax of isdigit()
The isdigit() function is defined inside the <cctype> header file.
isdigit(c);
Parameter
- c: Character to check if it is a digit.
Return Value
- Returns non-zero (true) if the character is a digit ('0'–'9').
- Returns 0 (false) otherwise.
Working of isdigit() Function
As all the characters in C++ are represented by their ASCII values and all the characters representing numeric digits lies in the range [48, 57]. The isdigit() function works by checking if the ASCII value of the given character lies in the range from 48 to 57 (or '0' to '9').
- If the character falls within this range, it returns a non-zero value (true).
- Otherwise, it returns 0 (false).
Examples of isdigit()
Below are some common use cases of the isdigit() function in C++ that demonstrate its use in validating and processing numeric characters.
Sum of Digits in a String
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
string s = "g1f2g3";
int sum = 0;
for (char c : s) {
// If the given character is a digit
// Convert it to int and add
if (isdigit(c))
sum += c - '0';
}
cout << sum;
return 0;
}
Phone Number Validation
As a phone number should only contain numbers, a string representing a phone number should only contains characters that represent numbers.
C++
#include <iostream>
#include <cctype>
using namespace std;
int main() {
// Here alphabet 'O' is used instead of '0'
string ph_num = "9124782O21";
// Check if all characters are numbers
for (char c : ph_num) {
if (!isdigit(c)) {
cout << "Invalid number!";
return 0;
}
}
cout << "Valid number";
return 0;
}
Explore
C++ Basics
Core Concepts
OOP in C++
Standard Template Library(STL)
Practice & Problems
My Profile