I am trying to get my program to write in a separate function than the main function, and I’m having a good deal of trouble. Here is 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;
}
Your
writeToFilefunction is trying to use theoutputFilevariable which is in a different scope. You can pass the output stream to the function and that should work.