开发者

Why does this code continuously print newlines?

 in开发者_Go百科t 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';
}


An istream_iterator reaches its end when an input error or end-of-file occurs (buffer overrun which may happen with your vector doesn't count :) ).

Once cin is in error or EOF state, all subsequent input operations will fail (unless you cin.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*column characters (perhaps discarding newlines in the input).


Ummm, you have a cout << '\n'; inside that loop... so it'll print a newline for each time it goes through the loop.


You need to initialise your variables, row and column (probably to 0). It's a good habit to get in to.


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.


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, " "));


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?


Did you maybe intend to initialize your row and column to some value and then decrement them or something? As it stands, sometimes your code will continue forever, sometimes it'll exit on the first run of the loop before it even does anything interesting.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜