Sum of digits in a string C++ Program

Sum of digits in a string C++ – find digits in a given string and calculate the sum of all digits. For example, if a given string is “hello65”; then sum of digits present in the string is 6+5 = 11.  isDigit() C++ library function will be used to check if char is a digits.

LOGIC:

  • Traverse the string within a for loop.
  • Check each character if it is a digit using isDigit() function.
  • Convert digit character to int value and sum.

Sum of digits in String C++ Code

/*-------------------------------------
* C++ program to extract digits from 
* string and calculate the sum of them.
* */

#include <cctype>//For C++ isDigit() function
#include<iostream>
using namespace std;

//char to int conversion
#define charToInt(c) (c-'0')

int main()
{
 int sum = 0;

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])){
 //dispaly digit characters
 cout << str[i] << ", ";

//convert charater to int
 int a = charToInt(str[i]);

//Sum digits
 sum = sum + a;
 }

}
 //Display Sum
 cout<<"\nSum of all Digits:"<<sum<<endl;

return 0;
}

Program Output:
String contains digits :6, 5,
Sum of all Digits:11

Related Posts