[Solved] Using iterator to read input [closed]


The code compiles because it is valid code. It just doesn’t do anything meaningful.

sin_start is not a function, it is a variable of type istream_iterator<int>, where istream_iterator is a template class defined in the <iterator> header file. It is being passed std::cin as a parameter to its constructor, so it knows which stream to read data from.

But the code simply exits after that variable is constructed. It is not trying to read any data. For that, try something more like this:

#include <iostream>
#include <iterator>
using namespace std;

int main() {
    cout << "Enter integers: ";
    istream_iterator<int> sin_start(cin), end;
    while (sin_start != end) {
        int value = *sin_start++;
        // do something with value...
    }
}

That will read integers until the user cancels input on the terminal.

However, in comments, you mention that you want to read integers until the user presses Enter instead. In that case, you need a different approach, since istream_iterator uses operator>> internally, which skips leading whitespace on each read, and Enter is treated as whitespace. Try something more like this instead:

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
    cout << "Enter integers: ";
    string line;
    getline(cin, line);
    istringstream iss(line);
    int value;
    while (iss >> value) {
        // do something with value...
    }
}

2

solved Using iterator to read input [closed]