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.
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) .
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.
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.
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
.
Exactly the same with the fstream instance instead of cin.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With