使用<<操作员同时写入文件和cout [英] Using << operator to write to both a file and cout

查看:78
本文介绍了使用<<操作员同时写入文件和cout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让<<运算符,将它需要的值写入文件和cout.我试图用下面的代码来做到这一点,但未能成功.它只是将值写入文本文件.任何帮助,将不胜感激.谢谢.

I'd like to overload << operator to write the value it takes to a file and cout. I have tried to do it with following code, but couldn't succeed it. It just writes the value to text file. Any help would be appreciated. Thank you.

void operator<<(std::ostream& os, const string& str)
{
    std::cout << str;
    os << str;
}

int main() {
    ofstream fl;
    fl.open("test.txt");
    fl << "!!!Hello World!!!" << endl;
    return 0;
}

推荐答案

创建一个帮助程序类和重载运算符,以处理流到两个流的问题.使用帮助程序类,而不要尝试覆盖已重载的operator<<函数的标准库实现.

Create a helper class and overload operators that takes care of streaming to two streams. Use the helper class instead of trying to override the standard library implementations of the overloaded operator<< functions.

这应该有效:

#include <iostream>
#include <fstream>

struct MyStreamingHelper
{
    MyStreamingHelper(std::ostream& out1,
                      std::ostream& out2) : out1_(out1), out2_(out2) {}
    std::ostream& out1_;
    std::ostream& out2_;
};

template <typename T>
MyStreamingHelper& operator<<(MyStreamingHelper& h, T const& t)
{
   h.out1_ << t;
   h.out2_ << t;
   return h;
}

MyStreamingHelper& operator<<(MyStreamingHelper& h, std::ostream&(*f)(std::ostream&))
{
   h.out1_ << f;
   h.out2_ << f;
   return h;
}

int main()
{
   std::ofstream fl;
   fl.open("test.txt");
   MyStreamingHelper h(fl, std::cout);
   h << "!!!Hello World!!!" << std::endl;
   return 0;
}

这篇关于使用&lt;&lt;操作员同时写入文件和cout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆