Open In App

Reading Lines by Lines From a File to a Vector in C++ STL

Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisites:

The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators.

Vector in C++ STL

Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. 

Reading Lines by Lines From a File to a Vector in C++ STL

In this article, we will see how to read lines into a vector and display each line. We will use File Handling concepts for this.

Reading Files line by line

First, open the file i.e.

//open the file

ifstream file(“file.txt”);

Now keep reading the next line and push it in vector function until the end of the file i.e.

string str;

// Read the next line from File until it reaches the end.

while(file >> str){

//inserting lines to the vector. 

         v.push_back(str);
}

Example 1:

C++




// C++ Program to implement Reading
// In Lines From A File To A Vector
#include <bits/stdc++.h>
 
using namespace std;
 
int main()
{
    // Opening the file
    ifstream file("file.txt");
 
    vector<string> v;
    string str;
 
    // Read the next line from File until it reaches the
    // end.
    while (file >> str) {
        // Now keep reading next line
        // and push it in vector function until end of file
        v.push_back(str);
    }
 
    // Printing each new line separately
    copy(v.begin(), v.end(),
         ostream_iterator<string>(cout, "\n"));
 
    return 0;
}


Output:

Output for the code with the file name "file.txt"

Output for the code with the file name “file.txt”

Example 2:

C++




// C++ Program to read lines
// From A File To A Vector
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
 
using namespace std;
int main()
{
 
    fstream myfile;
 
    // open file
    myfile.open("file1.txt");
    vector<string> g1;
 
    if (myfile.is_open()) {
        // checking if the file is open
        string str;
 
        // read data from file object
        // and put it into string.
        while (getline(myfile, str)) {
            g1.push_back(str);
        }
        // close the file object.
        myfile.close();
    }
    cout << "\nVector elements are: " << endl;
    for (int i = 0; i < g1.size(); i++) {
        cout << g1[i] << endl;
    }
}


Output

Output of the vector elements



Last Updated : 01 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads