Search code examples
c++loopsioiostreamistream-iterator

Why does this code continuously print newlines?


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

Solution

  • 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).