Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write to file in separate function

Tags:

c++

file-io

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;
}
like image 669
Sam Maier Avatar asked Nov 22 '25 19:11

Sam Maier


1 Answers

Your writeToFile function is trying to use the outputFile variable which is in a different scope. You can pass the output stream to the 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;
}
like image 185
James Avatar answered Nov 24 '25 09:11

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!