Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ cout like function, which writes data to file (logging)

Tags:

c++

logging

cout

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!

like image 298
Anti Lippasaar Avatar asked Sep 03 '25 15:09

Anti Lippasaar


1 Answers

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

like image 187
YSC Avatar answered Sep 05 '25 05:09

YSC