How to easily indent output to ofstream?

前端 未结 7 1459
挽巷
挽巷 2020-12-09 04:34

Is there an easy way to indent the output going to an ofstream object? I have a C++ character array that is null terminate and includes newlines. I\'d like to output this

相关标签:
7条回答
  • 2020-12-09 05:04

    There is no simple way, but a lot has been written about the complex ways to achieve this. Read this article for a good explanation of the topic. Here is another article, unfortunately in German. But its source code should help you.

    For example you could write a function which logs a recursive structure. For each level of recursion the indentation is increased:

    std::ostream& operator<<(std::ostream& stream, Parameter* rp) 
    {
        stream << "Parameter: " << std::endl;
    
        // Get current indent
        int w = format::get_indent(stream);
    
        stream << "Name: "  << rp->getName();
        // ... log other attributes as well
    
        if ( rp->hasParameters() )
        {
            stream << "subparameter (" << rp->getNumParameters() << "):\n";
    
            // Change indent for sub-levels in the hierarchy
            stream << format::indent(w+4);
    
            // write sub parameters        
            stream << rp->getParameters();
        }
    
        // Now reset indent
        stream << format::indent(w);
    
        return stream; 
    
    }
    
    0 讨论(0)
提交回复
热议问题