4

For example if i want to use extraction operator on two object to send the same data tto two object for syntax shortcut

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

So then the data is applied to out_file and cout at same time? out_file is fstream..

Kelvin
  • 233
  • 1
  • 4
  • 13
  • 1
    Take a look at Boost's tee operator. See here: http://stackoverflow.com/questions/670465/using-boostiostreamstee-device – Joe Z Nov 10 '13 at 07:08

3 Answers3

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!
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
0

Unfortunately cout doesn't return ostream object, which contains all your output information. And you can't copy ostream object, which std::operator<< returns.

What you can is to create a function or an object, which combines all you output information and call this function as many times as you wish:

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

int main() {
  myPrint(cout);
  myPrint(file_out);
  myPrint(cerr);
}
klm123
  • 12,105
  • 14
  • 57
  • 95
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

odedsh
  • 2,594
  • 17
  • 17