Jan 3, 2012 at 2:04pm UTC
I am trying to write data to an output file from a C++ program, but i want this output file to appear on the console also. I think i have the code to make it write to the output file, but i dont know how to include this output file on the console. Anyone got any ideas?
Thanks.
Jan 3, 2012 at 2:08pm UTC
please explain what do you mean by having the output file on console.
Jan 3, 2012 at 3:43pm UTC
lol cout is the output to console....cout=console output.....>.<
Jan 3, 2012 at 9:47pm UTC
Here's part of one I made that will use one command to simultaneously output to the console and file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
class logger // Logging class that will write to console and file.
{
public :
logger(const char * filename) { fout.open(filename); }
~logger() { fout.flush(); fout.close(); }
template <class T>
friend logger& operator <<(Logger& log, const T& output);
friend logger& operator <<(logger& log, std::ostream& (*manip)(std::ostream &));
friend logger& operator <<(logger& log, std::ios_base& (*manip)(std::ios_base&));
private :
std::ofstream fout;
};
logger& operator <<(logger& log, std::ostream& (*manip)(std::ostream &))
{ // This function allows logger to accept std::endl and std::flush
manip(std::cout); manip(log.fout);
return log;
}
logger& operator <<(logger& log, std::ios_base& (*manip)(std::ios_base&))
{ // This function allows the logger to accept modifiers: std::hex, std::fixed
manip(std::cout); manip(log.fout);
return log;
}
//This function accepts parameterized modifiers: std::setw(5)
logger& operator <<(logger& log, std::_Smanip<std::streamsize> MySmanip) { return log; }
template <class T> //Accepts strings or values
logger& operator <<( logger& log, const T& output )
{
std::cout << output;
log.fout << output << std::flush;
return log;
}
Now just use it like this:
1 2
logger output("Logfile.txt" );
output << "text" << std::setprecision(5) << std::hex << 32 << std::endl;
Last edited on Jan 3, 2012 at 10:01pm UTC