Read input of unknown length

Problem:
Suppose you are given the following input:

5 22 9 813 13
77 98 93 51
5 3 1 5 7 1 3
9 1

Your task is to print out the sum of the numbers in each line, e.g. the sum for the first line is

5 + 22 + 9 + 813 + 13 = 862

So the output should be:

862
319
25
10

The problem here is that you don’t know how many lines you are given and how many numbers there are in each line. How can you solve this problem in Python and C++?

Solution:
In Python we can do the following:

from sys import stdin, stdout

def main():
    for line in stdin:
        L = [int(x) for x in line.split()]
        stdout.write(str(sum(L)) + '\n')

main()

In C++ the solution is a little longer:

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    string line;
    while (getline(cin, line)) {
        int total = 0;
        stringstream ss(line);
        int n;
        while (ss >> n) {
            total += n;
        }
        cout << total << '\n';
    }

    return 0;
}

References:
1. https://uva.onlinejudge.org/board/viewtopic.php?t=209042
2. http://stackoverflow.com/questions/7800638/how-to-read-n-integers-from-standard-input-in-c

Leave a comment