0

I need to deduce length of text file and save the numbers it contains (int) in a vector. I wrote' the code below:

    std::ifstream data(file_in);

    unsigned length=distance(std::istream_iterator<int>(data),std::istream_iterator<int>());

    copy(std::istream_iterator<int>(data),std::istream_iterator<int>(),vec.begin());

However, even if the length is correct, no number is saved into my vector, but if I remove the second line numbers are saved. I think it's a problem of iterator... but I don't know how to solve it, do I need to use the function advance?

user3758182
  • 119
  • 1
  • 2
  • 8

2 Answers2

0

I've no idea how you use length in your code but here is a small piece of code that do what you need:

std::ifstream data(file_in);
std::vector<int> vec;
std::copy(std::istream_iterator<int>(data), std::istream_iterator<int>(), 
          std::back_inserter(vec));

All the magic is handled by std::back_inserter. There's no need to compute the length of the file.

You can find here a similar problem.

Community
  • 1
  • 1
Hiura
  • 3,500
  • 2
  • 20
  • 39
0

There is no point trying to count the number of integers that way. You can only do that by parsing the file, and if you've done that, why parse it again?

std::ifstream data(file_in);
std::vector<int> vec;
int i;
while (data >> i)
{
    vec.push_back(i);
}
Neil Kirk
  • 21,327
  • 9
  • 53
  • 91