Visual Cout && 同时写入文件 C++

visual cout && write into file simultaneously c++

本文关键字:文件 C++ Cout Visual      更新时间:2023-10-16

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

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

是否有一种方法可以同时打印和写入文件?

cout&&helloworld <<hello<< endl; 

您可以通过使用辅助类和与之配套的函数来完成。

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