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.
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;
}
};