Check if char is number C++ – Using isDigit ()

Check if char is number C++ – Example to check if a character is a number or digit using isdigit(int c) library function.

Note that digits can be  0, 1, 2 ,3, 4, 5 ,6, 7, 8, 9 .

To use the function isDigit, the header file  #include <cctype> need to be included.

C++ Program example –  This program check if a character in string is a digit. For example, if input string is “hello65”, then this string will be traversed in for loop and isDigit function will check each character if it is digit. If it is a digit then it will print the digits e.g. 6 5 etc.

/*
* C++ check if char is a number/digit
*/

#include <cctype>
#include<iostream>
using namespace std;


int main()
{

std::string str = "hello65";

cout << "String contains digits :";

for (int i=0; i<str.length(); ++i)
 {
 //Check if char is digit
 if (isdigit(str[i])){
 cout << str[i] << " ";
 }

}

return 0;
}

Output:
String contains digits :6 5

Applications using isDigit() function.

Related Posts