Print only digits from a string in C++

In this tutorial, we will learn how to print only digits from a string in C++. Now, in order to print only the digits from a string in C++. First, we need to extract all the digits from the particular string. Thereafter we can print them on to the console.

There is an inbuilt string function isdigit() which is used for this purpose. The isdigit() function is used for checking whether a particular index associated with a value is a digit or not. If the value is digit the function returns True, otherwise false.

The isdigit() function is defined under the iostream header. The program illustrating the use of isdigit() function is discussed now. The program will also make use of the iostream header for input/output. And we will be making use of length() function for knowing the length of the string. The program is as follows :

//illustrating the use of isdigit() function
using namespace std;
int main()
    // here you can define any string to be checked
    string s="123456789code speedy987654321 happy learning";
    for(int i=0;i<s.length();i++)
     // the function checks whether particular string value is digit or not
            cout<<s[i]<<" "; // it prints all the digits on to the console
    return 0;

The output of the above function is :

1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1

At the place of the string s, you can define any string whose digits to be extracted. You can also make use of cin for inputting the string. Thereafter in order to check with isdigit() function, first we need to define the one more stream string which is under sstream header. Finally, word by word in that each value could be checked. And hence, all the digits can be extracted.

Also, read :

C++ program to remove a particular character from a string

Inserting an element into a specific position of a vector in C++


Leave a Reply

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