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
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';
}
Put
sum=0;
// at the top
ps
while(cin.peek()!='\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';
}