例如,如果我想在两个对象上使用提取运算符将相同的数据发送到两个对象以获得语法快捷方式
(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/