简体   繁体   中英

How to write to file in separate function

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 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;
}

You need to make your sub-function aware of outputFile . As written, that variable only exists inside of the 'main' function. You can change your function signature to:

void writeToFile(int x, ofstream of)

and call it like:

writeToFile(i, outputFile);

This will pass the variable to the sub-function so that it can be used in that scope as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM