Q:

C++ Saving variables in files

I am new to c++ and I am trying to find a way to make a program store information in a variable.  I don't understand how to make a file or variable save and be able to be reused the next time the program is open.  For instance, let`s say that I make a program that asks for a username and saves it in a variable, how would I be able to store that variable so that the program can actually fetch it in a later use? 

A:

You just need to save that variable in a file and read from that file the next time you run your program. 
Say, you have the variable int a; which you allocate a value to a=10.  You can save that variable in a text file with the following code:
  ofstream file;
  file.open ("filePath.txt");
  file << a;
  file.close();

If instead of one variable, you have a set of variables, you can either save them in different files or save all of them in a vector and save the vector in one single file.  The variables will be saved in order.  So you can use this to refer to any specific variable you need when you run your program again.  Here's how you save a vector, say std::vector<double> b = {1,2,3};
    ofstream output_file( filePath );
    ostream_iterator<int> output_iterator( output_file, "\n" );
    // Passing all the variables inside the vector from the beginning of the vector to the end. 
    copy( b.begin( ), b.end( ), output_iterator );

To read from the file again, just do this:
std::vector<double> newVector;
ifstream input_file( filePath.txt );
double tempVar;
while ( input_file >> tempVar )
{
    newVector.push_back( tempVar );
}

Make sure to #include <iostream> at the beginning of your code! :) 
Hope this helps!