samedi 27 juin 2015

Store stream in a variable for later use

In my code I have a place, where I have to pass the exact same operator<< stream to 2 different places. Once to an ofstream and once to cout:

m_logFileStream << "[" << now->tm_hour << ":" << now->tm_min << ":" << now->tm_sec << "]"
                << "[" << logLevelsStrings[(int)logline.logLevel] << "] "
                << logline.logString << endl;

        if(m_verbose)
        {
            cout << "[" << now->tm_hour << ":" << now->tm_min << ":" << now->tm_sec << "]"
                            << "[" << logLevelsStrings[(int)logline.logLevel] << "] "
                            << logline.logString << endl;
        }

m_logFileStream is an ofstream. If I would like to change the pattern I need to do it in 2 places. It would be more convienient top store it in a variable like this:

stringstream ss;
        ss      << "[" << now->tm_hour << ":" << now->tm_min << ":" << now->tm_sec << "]"
                << "[" << logLevelsStrings[(int)logline.logLevel] << "] "
                << logline.logString << endl;

        m_logFileStream << ss;

        if(m_verbose)
        {
            cout << ss;
        } 

But for some reason instead of a proper output I am getting random hex numbers. Im not sure what I am doing wrong here. I would apriciate all help!

Edit: cout << ss.str(); works but m_logFileStream << ss.str(); doesnt save anything to the file m_logFileStream is created for. Strange...

Aucun commentaire:

Enregistrer un commentaire