News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

C++ TIps: IO - (not) redirecting cin and cout

Started by ben2ong2, October 06, 2006, 11:16:11 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

ben2ong2

PROBLEM: Ejo Schrama <schrama@geo.tudelft.nl>

I couldn't find this in my C++ book, nor the FAQ's. Is it possible
to redirect text made by cout to a file (designed inside a c++
program) rather than standard output?


RESPONSE: You are not allowed to view links. Register or Login (Steve Clamage), 30 Aug 95

There is no portable way to redirect cout (or cin) from within a program.
For one thing, cin/cout are not fstreams.

A simple way to get the effect you want is this:

int process(istream&, ostream&); // this function does all the work

main()
{
   istream *in = &cin;   // default to standard input
   ostream *out = &cout;   // default to standard output

   if( ... ) in = new ifstream(...);  // connect to file
   if( ! in  !! ! *in ) ... //report error

   if( ... ) out = new ofstream(...); // connect to file
   if( ! out || ! *out ) ... // report error

   int result = process(*in, *out); // do the work

   // clean up files if not cin/cout
   if( in != &cin )   delete in;
   if( out != &cout ) delete out;
   return result;
}

Function 'process' gets references to whatever the input and output streams
are, which could even be strstreams created in main, as a simple extension
to the above.



You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login