5

I ran across a cool STL example that uses istream_iterators to copy from std input (cin) to a vector.

vector<string> col1;
copy(istream_iterator<string>(cin), istream_iterator<string>(),
    back_inserter(col));

How would I do something similar to read from a file-stream directly into a container? Let's just say its a simple file with contents:

"The quick brown fox jumped over the lazy dogs."

I want each word to be a separate element in the vector after the copy line.

Ken Bloom
  • 57,498
  • 14
  • 111
  • 168
John Humphreys
  • 37,047
  • 37
  • 155
  • 255

3 Answers3

11

Replace cin with file stream object after opening the file successfully:

ifstream file("file.txt");

copy(istream_iterator<string>(file), istream_iterator<string>(),
                                                 back_inserter(col));

In fact, you can replace cin with any C++ standard input stream.

std::stringstream ss("The quick brown fox jumped over the lazy dogs.");

copy(istream_iterator<string>(ss), istream_iterator<string>(),
                                                 back_inserter(col));

Got the idea? col will contain words of the string which you passed to std::stringstream.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
6

Exactly the same with the fstream instance instead of cin.

Nim
  • 33,299
  • 2
  • 62
  • 101
3

I don't think the copy function is needed since the vector has a constructor with begin and end as iterators.

Thus, I think this is OK for you:

ifstream file("file.txt");
vector<string> col((istream_iterator<string>(file)), istream_iterator<string>());

The redundant () is to remove the Most_vexing_parse

Mingliang Liu
  • 5,477
  • 1
  • 18
  • 13