int row,column;
for (;;) {
cin >> rows >> columns;
if (!rows && !columns) break;
vector<char> dots(rows * columns);
copy(istream_iterator<char>(cin), istream_iterator<char>(), dots.begin());
// process vector
copy(dots.begin(), dots.end(), ostream_iterator<char>(cout, " "));
cout << '\n';
}
Why does this code continuously print newlines?
236 Views Asked by RaouL AtThere are 7 best solutions below
On
Ummm, you have a cout << '\n'; inside that loop... so it'll print a newline for each time it goes through the loop.
On
You need to initialise your variables, row and column (probably to 0). It's a good habit to get in to.
On
Because of the:
for(;;)
Which stands for 'do this forever' combined with the fact that the rows and columns may never be both set to zero with cin.
Try typing in zeroes for the cin input and it might end.
Also write:
cout << endl;
That is just what I do because I like flushing buffers.
On
Well, it doesn't really answer your question, but you can combine your two copy into one, as
copy(istream_iterator<char>(cin), istream_iterator<char>(), ostream_iterator<char>(cout, " "));
On
I don't think this line:
copy(istream_iterator<char>(cin), istream_iterator<char>(), dots.begin());
is doing what you want it to do... I'm not sure if you can use copy with cin in this way, as I don't think istream_iterator<char>() will be an iterator pointing to the last element you want to read. Is this from an example somewhere?
An
istream_iteratorreaches its end when an input error or end-of-file occurs (buffer overrun which may happen with your vector doesn't count :) ).Once
cinis in error or EOF state, all subsequent input operations will fail (unless youcin.clear();the state) and the code ends up just displaying newlines.It's a bit unclear whether this is what you actually want. Perhaps you just want to read
rows*columncharacters (perhaps discarding newlines in the input).