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
sumvariable 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:
- The
stringvariablestris used to keep the user-input string. - It is using the
getlinemethod to read the user-input string and assigns it to thestrvariable. - The
findSummethod is used to find the sum of all numbers in a string.- It uses one
forloop to iterate through the characters of the string. - For each character, it uses the
isdigitmethod 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 thesumvariable. - It returns the
sumvariable to the caller function.
- It uses one
- The
mainfunction prints the calculated sum.
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 :21Method 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.

