Meldryt
Meldryt

Reputation: 109

concating multiple strings in one line c++

I tried to overload operator "<<" to get similar behaviour like with std::stringstream. I want to concate multiple strings in one line and pass them to another function after the last word in the line.

struct Log
{
    std::string outString;

    template<typename T>
    friend Log& operator<<(Log& log, const T& t)
    {
        std::stringstream temp;
        temp << t;
        std::string str = temp.str();
        log.outString += str;
        if(str == "endl" || str == "\n")
        {
            //end of line -> pass string to custom print function
        }
        return log;
    }
};

i get a segmentation fault in this line:

log.outString += str;

Should be called like this.

log << "blub: " << 123 << "endl";

Upvotes: 1

Views: 159

Answers (1)

Harry
Harry

Reputation: 2969

You are comparing an integer in the statement if(t == "endl" || t== "\n"), replace it with if(str == "endl" || str == "\n").

Here is the full code:

#include <iostream>
#include <string>
#include <sstream>

struct Logg
{
    std::string outString;

    template<typename T>
    friend Logg& operator<<(Logg& logg, const T& t)
    {
        std::stringstream temp;
        temp << t;
        std::string str = temp.str();
        logg.outString += str;
        if(str == "endl" || str == "\n")
        {
            //end of line -> pass string to custom print function
        }
        return logg;
    }
};

int main()
{
    struct Logg logg;
    logg << "blub: " << 123 << "endl";
    std::cout << logg.outString << std::endl;

    return 0;
}

Upvotes: 4

Related Questions