I have been this on days and I think I am missing something simple. This is how cout works:
cout << "Testing" << 5;
Note that inputs can be anything, string, int etc. Instead of cout I want to use Log, and catch all of the data and write it to file. This is wanted:
log << "Testing" << 5;
Closest I have gotten. Header:
class LogFile {
public:
void write(std::string input);
int operator<<(const char u[100]);
int operator<<(const int u);
};
C++
int LogFile::operator<<(const char u[100]) {
std::string s;
std::stringstream ss;
ss << u;
s = ss.str();
this->write(s);
return 0;
};
int LogFile::operator<<(const int u) {
std::string s;
std::stringstream ss;
ss << u;
s = ss.str();
this->write(s);
return 0;
};
Code which is ran (only "Testing" is written, int is ignored):
LogFile log;
log << "Testing" << 5;
Goal is to write a function which mimics cout, but instead of printing, data is written to file. Any advise or help is appreciated!
You could have a templated operator<<
:
#include <sstream>
struct Log
{
void write(std::string const& s);
template<class T>
Log& operator<<(T const& msg)
{
std::stringstream ss;
ss << msg;
write(ss.str());
return *this;
}
};
This would be a possible usage:
int main(int argc, char **argv)
{
Log log;
log << 8;
log << "Hello, " << "World!";
std::string msg("plop");
log << msg;
}
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With