Question

I'm trying to read from a ifstream fin and put it into a vector vec1 using istream_iterators. I've seen these things all over the place:

vector<int> vec1((istream_iterator<int>(fin)),istream_iterator<int>);

I want to keep the istream_iterators for later use, so I thought "This should work":

istream_iterator<int> iit(fin);
istream_iterator<int> eos;
vector<int> vec1(iit,eos);

... It doesn't work =( my vector is completly empty. (the file i read from is a txt-file with nothing but digits).

EDIT: The txt looks as follows:

06351784798452318596415234561
6641321856006
Was it helpful?

Solution

As per comment, the first sequence of digits is greater than the maximum value for an int so the input operation will fail resulting in the vector remaining empty.

You can obtain the maximum values for int, etc using the std::numeric_limits template:

std::cout << std::numeric_limits<int>::max() << "\n";

OTHER TIPS

As an intermediate step you might want to try iterating over the sequence immediately to see if there is something (probably not):

while (iit != eos) {
    std::cout << *iit++ << '\n';
}

If this doesn't print anything check that your stream is in good shape initially:

if (!fin) {
    std::cout << "file not opened!\n";
}

If the stream only contaibs digits and no spaces it probably overflows and reading an int just fails as a result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top