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

后端 未结 3 911
再見小時候
再見小時候 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:08

    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';
    }
    
    0 讨论(0)
  • 2021-01-20 18:17

    Put

    sum=0; // at the top

    ps

    while(cin.peek()!='\n'){
    
    
    }
    
    0 讨论(0)
  • 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<int> begin(in), end;
        int sum = accumulate(begin, end, 0);
        cout << sum << '\n';
    }
    
    0 讨论(0)
提交回复
热议问题