Google News
logo
C++ Program to find number of Digits and White Spaces in a String
In the following example of C++ program that finds the number of digits and white spaces in a string :
Program :
#include <iostream>
#include <string>

using namespace std;

int main() {
    string str;
    int digits = 0, spaces = 0;

    cout << "Enter a string: ";
    getline(cin, str);

    for (int i = 0; i < str.length(); i++) {
        if (isdigit(str[i])) {
            digits++;
        } else if (isspace(str[i])) {
            spaces++;
        }
    }

    cout << "The number of digits in the string is: " << digits << endl;
    cout << "The number of white spaces in the string is: " << spaces << endl;

    return 0;
}
Output :
Enter a string: Free Time Learning 9963

The number of digits in the string is: 4

The number of white spaces in the string is: 3
This program prompts the user to enter a string, reads the input string using getline(), and then uses a for loop to iterate through each character in the string. If the character is a digit, it increments the digits counter.

If the character is a whitespace, it increments the spaces counter. Finally, it prints out the number of digits and white spaces in the string.