0

In my application I have a console (which uses std::out) and a window (that has a function to show some text). What I'm looking for is a way to show the last line of cout in my window. I've read some articles about making a custom streambuf class or a struct that simply overloads the << operator. I can't overload the << operator because I'm not able to use things like endl if I do so.

Another post here suggest to define my own streambuf but I don't know if that's a good solution for my problem. Maybe someone can give me an advice on how I should implement this feature.

Community
  • 1
  • 1
Timo
  • 9,269
  • 2
  • 28
  • 58
  • 1
    What exactly do you mean by "the last line of cout", and by "my window"? –  Jan 14 '17 at 17:25
  • By last line I mean everything that went through cout since the last '\n' char and my window is a PCLVisualizer from the point cloud library that has a function addText(...) where I can show some text. – Timo Jan 14 '17 at 17:30

1 Answers1

1

You can overload << for that purpose. To make it work with stream manipulators, you could use an internal std::stringstream:

class out
{
    std::ostringstream ss;
    std::string display_str;
  public:
    template <typename T> out &operator<<(T &&obj)
    {
        std::cout << obj;
        ss.str("");
        ss << obj;
        std::string tmp = ss.str();
        if (tmp.size() == 0)
            return *this;
        const char *ptr = &tmp[0], *start = ptr;
        while (*ptr)
        {
            if (*ptr == '\n')
                start = ptr+1;
            ptr++;
        }
        if (start != ptr)
            display_str = start;
        else
            display_str += start;
        update_display_string(display_str); // Replace this with your update function.
        return *this;
    }
};
HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
  • I had a similar approach on this but the problem is that stream manipulator can't resolve char and traits type in custom types and I don't want to write `endl>` each time. I could use a macro though – Timo Jan 14 '17 at 19:38
  • Rather, use a `tee`-like stream buffer. James Kanze once wrote an article about it. Oh yes, it's linked to in the OP's linked SO question, (http://stackoverflow.com/a/528661/464581). – Cheers and hth. - Alf Jan 14 '17 at 20:41