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

梦想的初衷 提交于 2019-12-02 00:37:28

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';
}

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';
}

Put

sum=0; // at the top

ps

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


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