Reading Lines by Lines From a File to a Vector in C++ STL
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++
#include <bits/stdc++.h>
using namespace std;
int main()
{
ifstream file( "file.txt" );
vector<string> v;
string str;
while (file >> str) {
v.push_back(str);
}
copy(v.begin(), v.end(),
ostream_iterator<string>(cout, "\n" ));
return 0;
}
|
Output:
Output for the code with the file name “file.txt”
Example 2:
C++
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
fstream myfile;
myfile.open( "file1.txt" );
vector<string> g1;
if (myfile.is_open()) {
string str;
while (getline(myfile, str)) {
g1.push_back(str);
}
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
Share your thoughts in the comments
Please Login to comment...