whats wrong with my ofstream?

Hi All,
Im wondering why the bit of code isnt working ...
Basically its a simple function that takes a vector and a string. It is supposed to output the values in the vector to a. the screen and b. a file. It will write the vector's values to the screen alright but writes nothing to the file. What am I doing wrong?

Your code looks like it creates a new ofstream instance called a_file which due to scoping rules closes the file immediately once the closing brackets are reached (the ofstream object's destructor is called) and before any output statements get called.

You should also test the stream to make sure it is open before writing to it.

"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens

The problem with your code is that you declared your ostream object twice:

Code:

ofstream a_file;
if (id == "one"){
ofstream a_file ("dataone.txt");
}

The first declaration created a variable called a_file that was global to your function. The second declaration created a variable called a_file that was local to the braces surrounding it, i.e the if statement, and which hid the global variable. The local variable is constructed but goes out of existence as soon as you exit the block containing it, leaving you with an unassigned a_file global variable.

You had the right intention by declaring your a_file variable outside of the if statement, but you mistakenly redeclared it inside the if blocks creating a new variable instead of making an assignment to the existing variable. You don't need to call open(), you just need to fix that problem.