Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use std::copy to read directly from a file stream to a container?

Tags:

c++

stl

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.

like image 455
John Humphreys Avatar asked Aug 22 '11 19:08

John Humphreys


People also ask

How does STD copy work?

std::copy, std::copy_if. Copies the elements in the range, defined by [first, last) , to another range beginning at d_first . 1) Copies all elements in the range [first, last) starting from first and proceeding to last - 1. The behavior is undefined if d_first is within the range [first, last) .

How do you read from a file to a string C++?

Read whole ASCII file into C++ std::string Begin Declare a file a. txt using file object f of ifstream type to perform read operation. Declare a variable str of string type. If(f) Declare another variable ss of ostringstream type.

How do I read a whole file in CPP?

File Handling in C++Create a stream object. Connect it to a file on disk. Read the file's contents into our stream object. Close the file.


2 Answers

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.

like image 162
Nawaz Avatar answered Oct 13 '22 18:10

Nawaz


Exactly the same with the fstream instance instead of cin.

like image 42
Nim Avatar answered Oct 13 '22 19:10

Nim