How to write a file in a separate function
I am trying to get my program to write in a separate function than the main function and am having a lot of problems. Here's a simplified version of my program:
#include <iostream>
#include <fstream>
using namespace std;
void writeToFile(int x)
{
outputFile << x << endl;
}
int main()
{
ofstream outputFile;
outputFile.open("program3data.txt");
for (int i = 0; i < 10; i++)
{
writeToFile(i);
}
outputFile.close();
return 0;
}
+3
source to share
2 answers
Your function is writeToFile
trying to use a variable outputFile
that is in a different scope. You can pass the output stream to a function and that should work.
#include <iostream>
#include <fstream>
using namespace std;
void writeToFile(ofstream &outputFile, int x)
{
outputFile << x << endl;
}
int main()
{
ofstream outputFile;
outputFile.open("program3data.txt");
for (int i = 0; i < 10; i++)
{
writeToFile(outputFile, i);
}
outputFile.close();
return 0;
}
+5
source to share
You need to make your subfunction aware of outputFile
. As written, this variable only exists inside the main function. You can change your function signature:
void writeToFile(int x, ofstream of)
and call it like this:
writeToFile(i, outputFile);
This will pass the variable to a subfunction so that it can also be used in this scope.
+1
source to share