Prerequisite:
The C++ Normal Template Library (STL) gives a number of helpful container lessons that can be utilized to retailer and manipulate information. One of the vital generally used container lessons is the vector. On this article, we are going to talk about easy methods to copy the contents of a file right into a vector utilizing C++ STL.
Strategy:
The essential strategy to repeat a file right into a vector is to open the file, learn its contents, and retailer them within the vector. The C++ STL gives a number of features that can be utilized to perform this activity. Essentially the most generally used features are the ifstream class and the vector’s push_back() perform. The ifstream class is used to open a file for studying. As soon as the file is open, we will use the >> operator to learn the contents of the file one character at a time and retailer them within the vector. The push_back() perform is used so as to add a component to the top of the vector.
Instance:
C++
|
|
Output:
“instance.txt” file
Output
On this instance, the file “instance.txt” is opened for studying utilizing the ifstream class. The contents of the file are learn one character at a time and saved within the vector “v” utilizing the push_back() perform. Lastly, the contents of the vector are printed to the display screen.
Be aware: Ensure that the file exists in the identical listing because the code or that you simply present the right path of the file.