加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 是否可以同时在两个对象上使用插入操作符?

发布时间:2020-12-16 07:06:31 所属栏目:百科 来源:网络整理
导读:例如,如果我想在两个对象上使用提取运算符将相同的数据发送到两个对象以获取语法快捷方式 (out_file,cout) "nnTotal tokens found: " statistics[0] "nnAlphaNumeric Tokens: " statistics[1] "nnPunctuation character found: " statistics[2] "nNum
例如,如果我想在两个对象上使用提取运算符将相同的数据发送到两个对象以获取语法快捷方式

(out_file,cout) << "nnTotal tokens found: " << statistics[0] << "nnAlphaNumeric Tokens: " << statistics[1]
                << "nnPunctuation character found: " << statistics[2] << "nNumber of whitespace: " << statistics[3]
                << "nNumber of newlines: " << statistics[4] << "nnTokens are stored in out filennPress Enter to exit....";

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

解决方法

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

teeing.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!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读