例如,如果我想在两个对象上使用提取运算符将相同的数据发送到两个对象以获取语法快捷方式
(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 ..
答案 0 :(得分:1)
您可以使用boost::iostreams::tee_device
将数据发送到一对流。
#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!
答案 1 :(得分:0)
不幸的是,cout不会返回包含所有输出信息的ostream对象。你不能复制ostream对象,std :: operator&lt;&lt;回报。
您可以创建一个函数或对象,它将所有输出信息组合在一起,并根据需要多次调用此函数:
void myPrint(std::ostream& os){
os << "AA" << "BB" << "CC" << std::endl;
}
int main() {
myPrint(cout);
myPrint(file_out);
myPrint(cerr);
}
答案 2 :(得分:0)
您应该使用boost
中的tee流过滤器http://www.boost.org/doc/libs/1_54_0/libs/iostreams/doc/index.html
这是一个完全相同的模板设备..您还可以阅读本文,其中主要介绍如何快速构建一个: http://wordaligned.org/articles/cpp-streambufs