简体   繁体   中英

istream_iterator to initialize vector

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM