C++ Reading fixed number of lines of integers with unknown number of integers in each line

后端 未结 3 915
再見小時候
再見小時候 2021-01-20 17:36

I\'m trying to read in data and solve simple problem, data :

3               - number of lines to read in
1 1
2 2 2
3 4 

after each line is

3条回答
  •  深忆病人
    2021-01-20 18:28

    C++ gives you many tools:

    • string is a class managing the lifetime of character strings.
    • getline puts a line from a stream (up to the next newline) into a string.
    • istringstream makes an istream out of a string
    • istream_iterator iterates over an istream, extracting the given type, breaking on whitespace.
    • accumulate takes iterators delimiting a range and adds together the values:

    Altogether:

    string line;
    while (getline(cin, line)) {
        istringstream in(line);
        istream_iterator begin(in), end;
        int sum = accumulate(begin, end, 0);
        cout << sum << '\n';
    }
    

提交回复
热议问题