user2030677
user2030677

Reputation: 3526

Having trouble reading file into vector

I have a file that has three ints on three rows. It looks like this:

000
001
010

And I'm trying to read each integer into the vector positions but I don't know if I'm doing it right. Here is my code:

#include <fstream>
#include <iterator>
#include <vector>

int main()
{
   std::vector<int> numbers;
   std::fstream out("out.txt");

   std::copy(std::ostreambuf_iterator<int>(out.rdbuf()),
             std::ostreambuf_iterator<int>(), std::back_inserter(numbers));
}

What am I doing wrong here? I'm getting a "no matching function call" error on the line where I do the copy.

Upvotes: 3

Views: 868

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361422

You're using wrong iterator.

You need istreambuf_iterator, not ostreambuf_iterator:

 std::copy(std::istreambuf_iterator<int>(out.rdbuf()),
           std::istreambuf_iterator<int>(), std::back_inserter(numbers));

Note that ostreambuf_iterator is an output iterator. It is used to write, not read. What you want to do is, read for which you need istreambuf_iterator.

But wait! The above code is not going to work either, Why?

Because you're using istreambuf_iterator and passing int to it. The istreambuf_iterator reads data as unformatted buffer of type either char* or wchar_t*. The template argument to istreambuf_iterator could be either char or wchar_t.

What you actually need is called istream_iterator which reads formatted data of given type:

std::copy(std::istream_iterator<int>(out), //changed here also!
          std::istream_iterator<int>(), std::back_inserter(numbers));

This will work great now.

Note that you could just avoid using std::copy, and use the constructor of std::vector itself as:

std::fstream in("out.txt");

std::vector<int> numbers((std::istream_iterator<int>(in)), //extra braces
                         std::istream_iterator<int>());

Note the extra braces around first argument which is used to avoid vexing parse in C+++.

If the vector object is already created (and optionally it has some elements in it), then you can still avoid std::copy as:

numbers.insert(numbers.end(), 
               std::istream_iterator<int>(in), //no extra braces
               std::istream_iterator<int>());

No extra braces needed in this case.

Hope that helps.

Upvotes: 10

user2214436
user2214436

Reputation: 23

Read the Book 'C++ How To Program' by Dietal & Dietal, The chapter on Vectors. I assure you, all your problems will be solved. You have opened the text file for output instead of input. Instead of using this function I would suggest that you should read-in strings and copy them into your vector using iterators until EOF is encountered in the file. EDIT: This way is more natural and easy to read and understand if you are new to Vectors.

Upvotes: 0

Related Questions