stock a file in a vector cpp
To stock a file in a vector in C++, you can follow these steps:
- Include the necessary header files:
#include <iostream>
#include <fstream>
#include <vector>
Here, we include the necessary header files. The iostream
header is required for input/output operations, fstream
is needed for file handling, and vector
is used to store the contents of the file.
- Create an input file stream object and open the file:
std::ifstream inputFile;
inputFile.open("filename.txt");
Here, we create an input file stream object called inputFile
and open the file "filename.txt". Make sure to replace "filename.txt" with the actual name of the file you want to stock in the vector.
- Create a vector to store the file contents:
std::vector<std::string> fileContents;
Here, we create a vector called fileContents
to store the contents of the file. In this example, we assume that each line of the file contains a string.
- Read the file line by line and store each line in the vector:
std::string line;
while (std::getline(inputFile, line)) {
fileContents.push_back(line);
}
Here, we use a while
loop to read each line of the file using the getline
function. The getline
function reads a line from the file and stores it in the line
variable. Then, we use the push_back
function to add the line
to the fileContents
vector.
- Close the file:
inputFile.close();
After reading the file, it is important to close it using the close
function to free up system resources.
Now, the fileContents
vector contains all the lines of the file. You can access and manipulate the contents as needed.