2 ways in C++ to find the sum of digits in a String

C++ program to find the sum of digits in a String:

In this program, I will show you how to find the sum of all digits in a String in C++ in two different ways. We will take the string from the user as input.

Method 1: By using a for loop:

With this approach, the program will use a for loop to iterate over the characters to find the sum of digits in a String. It will use the following steps:

  • Get the string from the user.
  • Initialize one variable as 0 to hold the sum of digits.
  • Iterate over the characters of the string one by one.
  • Check if the current character is a digit or not. If it is a digit, add it to a sum variable.
  • At the end of the program, print the sum variable to the user.

C++ program to find the sum of digits of a string with a for loop:

The following C++ program uses a for loop to find sum of digits in a string:

#include <iostream>

using namespace std;

int findSum(string str)
{
    int sum = 0;

    for (char ch : str)
    {
        if (isdigit(ch))
        {
            sum += ch - '0';
        }
    }
    return sum;
}

int main()
{
    string str;
    cout << "Enter a string:" << endl;

    getline(cin, str);
    cout << "Sum: " << findSum(str) << endl;
}

Download it on GitHub

Explanation:

  1. The string variable str is used to keep the user-input string.
  2. It is using the getline method to read the user-input string and assigns it to the str variable.
  3. The findSum method is used to find the sum of all numbers in a string.
    1. It uses one for loop to iterate through the characters of the string.
    2. For each character, it uses the isdigit method to check if the character is a digit or not. If it is a digit, it converts that character to a number and adds that value to the sum variable.
    3. It returns the sum variable to the caller function.
  4. The main function prints the calculated sum.

C++ sum of digits of a string example

Sample Output:

If you run the above program, it will print output as below:

hello world 123 !
Sum :6

Enter a string:
hello 1 world 23456 !
Sum :21

Method 2: By comparing the character with digits:

We can also compare the characters with '0' and '9' instead of using the isdigit method. The following program shows how to write the program by comparing the characters with '0' and '9':

#include <iostream>

using namespace std;

int findSum(string str)
{
    int sum = 0;

    for (char ch : str)
    {
        if (ch >= '0' && ch <= '9')
        {
            sum += ch - '0';
        }
    }
    return sum;
}

int main()
{
    string str;
    cout << "Enter a string:" << endl;

    getline(cin, str);
    cout << "Sum: " << findSum(str) << endl;
}

Download it on GitHub

It compares the value of ch with '0' and '9'. If you run this program, it will print similar results.

You might also like: