Calculate sum of all numbers present in a string | C ++ program to calculate sum of all numbers present in a string containing alphanumeric characters ; Function to calculate sum of all numbers present in a string containing alphanumeric characters ; A temporary string ; holds sum of all numbers present in the string ; read each character in input string ; if current character is a digit ; if current character is an alphabet ; increment sum by number found earlier ( if any ) ; reset temporary string to empty ; atoi ( temp . c_str ( ) ) takes care of trailing numbers ; Driver code ; input alphanumeric string ; Function call
#include <iostream> NEW_LINE using namespace std ; int findSum ( string str ) { string temp = " " ; int sum = 0 ; for ( char ch : str ) { if ( isdigit ( ch ) ) temp += ch ; else { sum += atoi ( temp . c_str ( ) ) ; temp = " " ; } } return sum + atoi ( temp . c_str ( ) ) ; } int main ( ) { string str = "12abc20yz68" ; cout << findSum ( str ) ; return 0 ; }