2

How can we print data on screen and save it to text at same time ?

ofstream helloworld;
string hello ="welcome";
helloworld.open("helloworld.txt");
**helloworld << hello <<endl;
cout << hello << endl;**

is there a way to print and write file simultaneously ??

cout&&helloworld <<hello<< endl; 
Rk1
  • 158
  • 5
  • 1
    Why not create a method that takes two inputs 1) a file output handle, and 2) the line/string to output? In that routine, the `cout` and `file.write` can be executed in that routine instead of duplication elsewhere. – localhost Sep 03 '15 at 02:57
  • Look into *logging frameworks* – M.M Sep 03 '15 at 04:03
  • http://stackoverflow.com/questions/9764314/mirror-console-output-to-file-in-c ? – Vlad Feinstein Sep 03 '15 at 16:17

1 Answers1

3

You can accomplish that by using a helper class and functions to go with it.

// The class
struct my_out
{
   my_out(std::ostream& out1, std::ostream& out2) : out1_(out1), out2_(out2) {}

   std::ostream& out1_;
   std::ostream& out2_;

};

// operator<<() function for most data types.
template <typename T>
my_out& operator<<(my_out& mo, T const& t)
{
   mo.out1_ << t;
   mo.out2_ << t;
   return mo;
}

// Allow for std::endl to be used with a my_out
my_out& operator<<(my_out& mo, std::ostream&(*f)(std::ostream&))
{
   mo.out1_ << f;
   mo.out2_ << f;
   return mo;
}

You'll have to add similar helper functions to deal with objects from <iomanip>.

Use it as:

std::ofstream helloworld;
helloworld.open("helloworld.txt");
my_out mo(std::cout, hellowworld);

string hello ="welcome";
mo << hello << std::endl;
R Sahu
  • 204,454
  • 14
  • 159
  • 270