Anti Lippasaar
Anti Lippasaar

Reputation: 83

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

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!

Upvotes: 4

Views: 4179

Answers (3)

Pete Becker
Pete Becker

Reputation: 76235

"function which mimics cout" -- cout is not a function. It is an object. What you're trying to do is to create an object that can be used with stream inserters and writes to a log file. std::ofstream may be of use here.

Upvotes: 1

YSC
YSC

Reputation: 40060

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

Upvotes: 4

SergeyA
SergeyA

Reputation: 62553

To answer the question as asked (although the goal would be better served using different approach):

Your operator << return 0 - an integral type. When you call operator<< on the return value, you end up calling built in bitwise shift operator, which just bitwise shifts 0 by 5, discarding the result.

You would see compilation error if you'd try to log << "Testing" << "Testing";

To fix the code, your operator<< should return a reference to *this - the object of type LogFile.

Upvotes: 1

Related Questions