简体   繁体   English

如何调用cout函数到ofstream输出文件

[英]how to call a cout function to ofstream output file

I have a function void displayList() that displays a list of a set. 我有一个函数void displayList(),它显示一组列表。 in the main function I also have 在主要功能中我也有

ofstream outputFile(output.txt)

how do I call displayList and prints it in output.txt? 如何调用displayList并将其打印在output.txt中? Thanks. 谢谢。

displaylist is just some bunch of cout lines displaylist只是一些提示行

Let's assume your DisplayList is currently something like: 假设您的DisplayList当前类似于:

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. 然后,您现有的代码可以继续不带参数调用DisplayList()并获取当前行为。 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 . 然后输出将到达指定的文件而不是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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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