Reading a file into a container

suggest change

In the example below we use std::string and operator>> to read items from the file.

std::ifstream file("file3.txt");

std::vector<std::string>  v;

std::string s;
while(file >> s) // keep reading until we run out
{
    v.push_back(s);
}

In the above example we are simply iterating through the file reading one “item” at a time using operator>>. This same affect can be achieved using the std::istream_iterator which is an input iterator that reads one “item” at a time from the stream. Also most containers can be constructed using two iterators so we can simplify the above code to:

std::ifstream file("file3.txt");

std::vector<std::string>  v(std::istream_iterator<std::string>{file},
                            std::istream_iterator<std::string>{});

We can extend this to read any object types we like by simply specifying the object we want to read as the template parameter to the std::istream_iterator. Thus we can simply extend the above to read lines (rather than words) like this:

// Unfortunately there is  no built in type that reads line using >>
// So here we build a simple helper class to do it. That will convert
// back to a string when used in string context.
struct Line
{
    // Store data here
    std::string data;
    // Convert object to string
    operator std::string const&() const {return data;}
    // Read a line from a stream.
    friend std::istream& operator>>(std::istream& stream, Line& line)
    {
        return std::getline(stream, line.data);
    }
};

std::ifstream file("file3.txt");

// Read the lines of a file into a container.
std::vector<std::string>  v(std::istream_iterator<Line>{file},
                            std::istream_iterator<Line>{});

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


File I/O:
* Reading a file into a container

Table Of Contents
8 Arrays
11 Loops
38 File I/O
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype