Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

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:

Flowchart: Sum of all positive integers in a sentence

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?