cout&&同时写入文件c ++

时间:2015-09-03 02:43:31

标签: c++ visual-c++

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

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

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

cout&&helloworld <<hello<< endl; 

1 个答案:

答案 0 :(得分:2)

你可以通过使用辅助类和函数来实现它。

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

您必须添加类似的辅助函数来处理来自<iomanip>的对象。

将其用作:

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

string hello ="welcome";
mo << hello << std::endl;
相关问题