Skip to content

Printing to stringstream and retaining formatting #116

Closed

Description

@mike-5345

Hello,

I want to be able to print a table to a stringstream but when I do this the special formatting (colour, boldness, etc.) is not retained.

I want to be able to pass around the table as a string in memory. Is there a way to do this?

Thanks,
Mike

Activity

  1. p-ranav commented on Apr 2, 2024

    @p-ranav
    Owner

    Could you redirect std::cout to a buffer? I'm not sure if this works but it's worth a try.

    std::stringstream buffer;
    std::streambuf* prevcoutbuf = std::cout.rdbuf(buffer.rdbuf());
    
    // print your table
    std::cout << yourTable << std::endl;
    
    // Get the table as a string
    std::string text = buffer.str();
    
    // Restore original buffer before exiting
    std::cout.rdbuf(prevcoutbuf);
  2. suitmyself commented on Oct 15, 2024

    @suitmyself

    Could you redirect std::cout to a buffer? I'm not sure if this works but it's worth a try.

    std::stringstream buffer;
    std::streambuf* prevcoutbuf = std::cout.rdbuf(buffer.rdbuf());
    
    // print your table
    std::cout << yourTable << std::endl;
    
    // Get the table as a string
    std::string text = buffer.str();
    
    // Restore original buffer before exiting
    std::cout.rdbuf(prevcoutbuf);

    not work

  3. nepto commented on Feb 1, 2025

    @nepto
    Contributor

    It actually does work.

    So let me summarize it. If you have table the standard way of printing is:

    std::cout << table;
    

    When you want to capture the string, you can use table.str().c_str()

    However, when you print it, the formatting (notably colors) is lost:

    printf("%s", table.str().c_str()); // formatting and colors are lost
    

    The workaround that @p-ranav provided is a good one and works as expected. You can capture the string and do whatever you want with it. Also print it with printf() with all the formatting retained:

    std::stringstream buffer;
    std::streambuf* prevcoutbuf = std::cout.rdbuf(buffer.rdbuf());
    std::cout << table << std::endl;
    std::string text = buffer.str();
    printf("%s", text.c_str()); // formatting and colors are good
    std::cout.rdbuf(prevcoutbuf);
    

    It would be great if Tabulate had a function for capturing the string, but this workaround works just fine.

  4. nepto commented on Sep 29, 2026

    @nepto
    Contributor

    Quick follow-up to my comment above: the rdbuf swap does not help if the table contains a nested table. That one loses its colors for a different reason.

    Fixed in #137

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions