简体   繁体   中英

how to call a cout function to ofstream output file

I have a function void displayList() that displays a list of a set. in the main function I also have

ofstream outputFile(output.txt)

how do I call displayList and prints it in output.txt? Thanks.

displaylist is just some bunch of cout lines

Let's assume your DisplayList is currently something like:

void DisplayList() { 
   cout << "a" << a << "\n";
}

I would rewrite it to become two overloaded functions:

void DisplayList(std::ostream &os) { 
    os << "a" << a << "\n";
}

void DisplayList() { DisplayList(std::cout); }

Then your existing code can continue to call DisplayList() with no parameters and get the current behavior. Code that wants to specify the destination file instead, can call:

Displaylist(outputFile);

And the output will got to the file they specified instead of cout .

This could be done as a function with a default argument instead, but under the circumstances, I think a pair of overloaded functions is probably simpler.

我相信是:

outputFile << displayList();

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