How to Save a Vector to a File in C++

The vector class in the C++ Standard Template Library serves as an alternative to the simple array. They are almost as fast as standard arrays, however they contain efficient functions for adding and removing elements from the array and are resized dynamically when needed. One useful member of the vector class is the iterator, which greatly simplifies the process of iterating through all the elements stored in the vector using a for-loop. The other tool used will be the ofstream object in the fstream library, which will let you use the simple "<<" operator for file output.

Things You'll Need

  • Computer
  • C++ compiler
  • Text editor or C++ IDE
Show More

Instructions

    • 1

      Create a C++ file named "vectorToFile.cpp". For this task, three libraries will be needed: fstream provides functionality for file I/O, iostream provides functionality for I/O to standard in and out, which will be rerouted from the console to a file in this activity, and vector provides the vector class. So start off with the following declarations:

      #include <fstream>
      #include <iostream>
      #include <vector>
      using namespace std;

    • 2

      Define the VectorToFile class. This class will be a bit simplistic. It will hold a vector and a function to save the vector to a file.

      class VectorToFile {
      public:
      vector<int> v;

      VectorToFile() {
      };

      void saveToFile() {
      };
      };

    • 3

      Write the saveToFile() method. Add the following lines of code, in order, to the saveToFile() method. First, get the file name from the user using the standard cin and cout commands, like so:

      char fileName[20];
      cout << "Enter the name of the file to use: ";
      cin >> fileName;

      Next, initialize the ofstream, or output file stream, with the file name and "ios::out". This will inform ofstream to be open for output only. Other possible options would be "ios::app", which instructs the stream to append data rather than overwrite it and "ios:binary", which instructs the stream to output in binary rather than text.

      ofstream vectorFile(fileName, ios::out);

      Finally, iterate through the array, using the iterator object of your vector.

      std::vector<int>::iterator i;
      for (i = v.begin(); i < v.end(); ++i) {
      vectorFile << *i;
      vectorFile << endl;
      }

    • 4

      Create a main function to test the class. Outside the class, declare the main function as follows:

      int main() {
      VectorToFile vtf;
      vtf.v.push_back(121);
      vtf.v.push_back(144);
      vtf.v.push_back(653);

      vtf.saveToFile();

      };

      Compile and run your new C++ program. Input a filename when asked.

Related Searches:

References

Comments

  • bugmenomore Jan 26, 2011
    dumb and not efficient

You May Also Like

Related Ads

Featured