【问题标题】:cout && write into file simultaneously c++cout && 同时写入文件 C++
【发布时间】:2015-09-03 02:43:31
【问题描述】:

我们如何在屏幕上打印数据并同时将其保存为文本?

ofstream helloworld;
string hello ="welcome";
helloworld.open("helloworld.txt");
**helloworld << hello <<endl;
cout << hello << endl;**

有没有办法同时打印和写入文件??

cout&&helloworld <<hello<< endl; 

【问题讨论】:

  • 为什么不创建一个接受两个输入的方法:1)一个文件输出句柄,以及 2)要输出的行/字符串?在该例程中,coutfile.write 可以在该例程中执行,而不是在其他地方重复。
  • 查看日志框架

标签: c++ visual-c++


【解决方案1】:

您可以通过使用辅助类和与之配套的函数来实现这一点。

// The class
struct my_out
{
   my_out(std::ostream& out1, std::ostream& out2) : out1_(out1), out2_(out2) {}

   std::ostream& out1_;
   std::ostream& out2_;

};

// operator<<() function for most data types.
template <typename T>
my_out& operator<<(my_out& mo, T const& t)
{
   mo.out1_ << t;
   mo.out2_ << t;
   return mo;
}

// Allow for std::endl to be used with a my_out
my_out& operator<<(my_out& mo, std::ostream&(*f)(std::ostream&))
{
   mo.out1_ << f;
   mo.out2_ << f;
   return mo;
}

您必须添加类似的辅助函数来处理来自&lt;iomanip&gt; 的对象。

将其用作:

std::ofstream helloworld;
helloworld.open("helloworld.txt");
my_out mo(std::cout, hellowworld);

string hello ="welcome";
mo << hello << std::endl;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 2010-11-15
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 2012-05-04
    相关资源
    最近更新 更多