4

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

(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..

4

3 回答 3

1

You can send data to a pair of streams using using a 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;
}

Build:

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

Run:

> ./teeing
This is a test!

Verify:

> cat ./out_file.log 
This is a test!
于 2013-11-10T07:40:06.213 回答
0

You should use the tee stream filter from boost

http://www.boost.org/doc/libs/1_54_0/libs/iostreams/doc/index.html

It is a template device that does exactly that.. You can also read this article that basically shows how to build one quickly: http://wordaligned.org/articles/cpp-streambufs

于 2013-11-10T07:18:21.613 回答
0

不幸的是 cout 不返回 ostream 对象,其中包含您的所有输出信息。而且您不能复制 std::operator<< 返回的 ostream 对象。

您可以创建一个函数或对象,它结合了所有输出信息并根据需要多次调用此函数:

void myPrint(std::ostream& os){
  os << "AA" << "BB" << "CC" << std::endl;
}

int main() {
  myPrint(cout);
  myPrint(file_out);
  myPrint(cerr);
}
于 2013-11-10T07:02:38.520 回答