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

江枫思渺然 提交于 2019-12-01 22:48:38

问题


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 entered I would like to obtain sum of entered numers, but number of integers in each line is unknown. After using above data screen should look like this :

3               
1 1
Sum: 2
2 2 2
Sum: 6
3 4 
Sum: 7

But from my algorithm I've got the output :

3
1 1
Sum: 1
2 2 2
Sum: 4
3 4
Sum: 3

I've written code, but it doesn't work properly (as above): EDITION
I improved my code and know it works properly without strings etc., proper code is below :

#include<iostream>
using namespace std;
int main()
{
    int x;
    int t, sum;
    cin >> t;

    for(int i=0; i<t; i++) {
        sum=0;
        while(true)
        {
            cin >> x;
            sum = sum + x;  
            if(cin.peek()=='\n')
                break; //conditional break
        }
        cout << "Sum: " << sum << "\n";
    }
    return(0);
}

回答1:


Read a line at a time, using getline, into an object of type std::string. Then use that std::string object to initialize an object of type std::istringstream, and use an extractor to read int values from the stream object until it fails. Then go back and read the next line. Roughly:

std::string line;
while (std::getline(std::cin, line)) {
    std::istringstream in(line);
    int sum = 0;
    int value = 0;
    while (in >> value)
        sum += value;
    std::cout << sum << '\n';
}



回答2:


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<int> begin(in), end;
    int sum = accumulate(begin, end, 0);
    cout << sum << '\n';
}



回答3:


Put

sum=0; // at the top

ps

while(cin.peek()!='\n'){


}


来源:https://stackoverflow.com/questions/15092172/c-reading-fixed-number-of-lines-of-integers-with-unknown-number-of-integers-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!