Home »
C++ Programs
C++ program to find the sum of all integers in a string using class
Submitted by Shubh Pachori, on September 01, 2022
Problem statement
Given a string, we have to find the sum of all integers in it using the class and object approach.
Example:
Input:
Enter String: add 12 and 13
Output:
Sum of all integers in String is 25
C++ code to find the sum of all integers in a string using the class and object approach
#include <bits/stdc++.h>
using namespace std;
// create a class
class String {
// private data member
private:
string str;
public:
// getString() function to insert string
void getString() {
cout << "Enter String:";
getline(cin, str);
}
// sumString() function to add all numerical values
// present in the string
int sumString() {
// initializing int type variables to
// perform operations
int index, number, sum;
// for loop to traverse the whole string
for (index = 0; str[index]; index++) {
// if condition to check if the character at
// index is a numerical or not
if (isdigit(str[index])) {
continue;
} else {
str[index] = ' ';
}
}
// stringstream allows us to read through
// the inserted string str
stringstream temp(str);
// while to add all numerical values
// in the inserted string
while (temp >> number) {
sum = sum + number;
}
// returning sum
return sum;
}
};
int main() {
// create an object
String S;
// int type variable to store the sum
int sum;
// getString() function to store the String
S.getString();
// sumString() function to add all
// numerical values in the string
sum = S.sumString();
cout << "Sum of all integers in String is " << sum;
return 0;
}
Output
RUN 1:
Enter String:10 and 20
Sum of all integers in String is 30
RUN 2:
Enter String: mp07nb9842
Sum of all integers in String is 9849
Explanation
In the above code, we have created a class named String, a string type data member str to store the string, and public member functions getString() and sumString() to store and to find out the sum of all integers in the string.
In the main() function, we are creating an object S of class String, reading the string by the user using getString() function, and finally calling the sumString() member function to find out the sum of all integers in the string. The sumString() function contains the logic to find out the sum of all integers in the string and printing the result.
C++ Class and Object Programs (Set 2) »