gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:20:42 25 4
gpt4 key购买 nike

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

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;

关于c++ - cout && 同时写入文件 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32366150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com