c++ - 是否可以同时在两个对象上使用插入运算符?

标签 c++ operator-keyword fstream cout istream

例如,如果我想在两个对象上使用提取运算符将相同的数据发送到两个对象以获得语法快捷方式

(out_file,  cout) << "\n\nTotal tokens found: " << statistics[0] << "\n\nAlphaNumeric Tokens: " << statistics[1]
                << "\n\nPunctuation character found: " << statistics[2] << "\nNumber of whitespace: " << statistics[3]
                << "\nNumber of newlines: " << statistics[4] << "\n\nTokens are stored in out file\n\nPress Enter to exit....";

那么数据同时应用到out_file和cout? out_file 是 fstream..

最佳答案

您可以使用 boost::iostreams::tee_device 将数据发送到一对流.

开球.cpp

#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/tee.hpp>

#include <fstream>
#include <iostream>

int main()
{
    typedef boost::iostreams::tee_device<std::ostream, std::ostream> Tee;
    typedef boost::iostreams::stream<Tee> TeeStream;

    std::ofstream out_file("./out_file.log");
    Tee tee(std::cout, out_file);

    TeeStream both(tee);

    both << "This is a test!" << std::endl;
}

构建:

> clang++ -I/path/to/boost/1.54.0/include teeing.cpp -o teeing

运行:

> ./teeing
This is a test!

验证:

> cat ./out_file.log 
This is a test!

关于c++ - 是否可以同时在两个对象上使用插入运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19887141/

相关文章:

c++ - C++)E0349没有运算符匹配这些操作数

java - 正则表达式匹配所有\p{L} 但不匹配\p{Alpha}

C++文件输出只接受第一个字

已经注册的类的Python boost to-Python转换器被忽略第二个转换方法

c++ - 为什么它需要一个右值复制构造函数,即使它不会被调用?

c++ - 添加所需库后使用 TShark C++ 源文件剖析消息时 undefined reference

c++ - 如何在 Arduino 的函数中定义全局数组的长度?

C++ 指向运算符的指针

c++ - 如果我要为C++程序获取行号,应该以什么格式写入.txt文件?

c++ - 使用 std::filebuf 时检测底层文件的完整性丢失?