create a file
Mar 11, 2012 at 7:25pm UTC
hello everyone.
i have some prbles creating a file i wnat the file show what i see in the C++ scream and it only show one number
how can i do that my file will be exactly like it shows me in the program when it run
please help
Mar 11, 2012 at 8:08pm UTC
Add this to your header or the top of your source file. You're welcome to split it into header/source.
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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
#include <iostream>
#include <fstream>
#include <iomanip>
class logger
{
public :
logger(const char * filename) // CTOR - Input is the filename that will be used for logging (good for debugging).
{
fout.open(filename);
}
~logger() // Destructor flushes and closes the file.
{
fout << std::flush;
fout.close();
}
template <class T>
logger& operator <<(const T& output) // Accepts chars/strings/doubles/ints/etc.
{
std::cout << output;
fout << output;
return *this ;
}
template <class Arg>
logger& operator <<(std::_Smanip<Arg> Smanip) // Overloaded for parameterized manipulators (setw, setprecision, etc..)
{
(*Smanip._Pfun)(std::cout, Smanip._Manarg);
(*Smanip._Pfun)(fout , Smanip._Manarg);
return *this ;
}
template <class Arg>
logger& operator <<(std::_Fillobj<Arg> Fillobj) // Overloaded for parameterized manipulator setfill()
{
std::cout.fill(Fillobj._Fill);
fout.fill (Fillobj._Fill);
return *this ;
}
logger& operator <<(std::ostream& (*manip)(std::ostream &)) // Overloaded for Output manipulators
{
manip(std::cout);
manip(fout);
return *this ;
}
logger& operator <<(std::ios_base& (*manip)(std::ios_base&)) // Overloaded for Basic format flags
{
manip(std::cout);
manip(fout);
return *this ;
}
private :
std::ofstream fout;
};
Then implement it like this:
1 2 3 4 5 6 7 8
int main()
{
logger log("output.txt" );
log << "Hello World" << std::endl;
return 0;
}
Now just always use
log
instead of
cout
Last edited on Mar 11, 2012 at 8:17pm UTC
Mar 11, 2012 at 10:15pm UTC
thank you
Topic archived. No new replies allowed.