ofstream in calling function

Hi,

I am trying to use ofstream to write in a txt file in a function called recurrently. for a simplified example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void func_write(double x) {
ofstream myfile;
myfile << "the result = " << x << endl;
}

int main() {
ofstream myfile;
myfile.open("result.txt");

double a = 1.0;
double b = 1.5;
double c = 2.5;
func_write(a);
func_write(b);
func_write(c);

myfile.close();
}

To this stage, it does not work, because the myfile in func_write cannot write in the txt file opened in main function. I don't want to open, append and close the txt file each time the function is called, that will take more time to execute all (imagine with 500 calls).

Could anyone please help me to make this work? Thanks a lot!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void func_write(double x, std::ofstream& myfile)
{
    myfile << "the result = " << x << std::endl;
}

int main()
{
    std::ofstream myfile("results.txt");
    double a(1.0), b(1.5), c(2.5);
    func_write(a, myfile);
    func_write(b, myfile);
    func_write(c, myfile);
    myfile.close();
}
Last edited on
Thanks! :)
Topic archived. No new replies allowed.