C++ Exercises: Sum of all positive integers in a sentence
C++ Basic: Exercise-78 with Solution
Write a C++ program to sum of all positive integers in a sentence.
Sample string: There are 12 chairs, 15 desks, 1 blackboard and 2 fans.
Output: 30
Sample Solution:
C++ Code :
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str1;
int sum_num = 0, num;
while (getline(cin, str1)) {
for (int i = 0; i < (int)str1.size(); i++) {
if (isdigit(str1[i])) continue;
else {
str1[i] = ' ';
}
}
stringstream abc(str1);
while (abc >> num) {
sum_num += num;
}
}
cout << "Sum of all positive integers: " << sum_num << endl;
return 0;
}
Sample Output:
Input number: 12 chairs, 15 desks, 1 blackboard and 2 fans Sum of all positive integers: 30
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to check whether two straight lines AB and CD are orthogonal or not.
Next: Write a C++ program to display all the leap years between two given years. If there is no leap year in the given period,display a suitable message.
What is the difficulty level of this exercise?