Formatting C++ console output

后端 未结 4 1741
孤城傲影
孤城傲影 2020-12-17 00:41

I\'ve been trying to format the output to the console for the longest time and nothing is really happening. I\'ve been trying to use as much of iomanip as I can

4条回答
  •  清酒与你
    2020-12-17 01:24

    You can write a procedure that always print the same number of characters to standard output.

    Something like:

    string StringPadding(string original, size_t charCount)
    {
        original.resize(charCount, ' ');
        return original;
    }
    

    And then use like this in your program:

    void list::displayByName(ostream& out) const
    {
        node *current_node  = headByName;
    
        out << StringPadding("Name", 30)
            << StringPadding("Location", 10)
            << StringPadding("Rating", 10)
            << StringPadding("Acre", 10) << endl;
        out << StringPadding("----", 30)
            << StringPadding("--------", 10)
            << StringPadding("------", 10)
            << StringPadding("----", 10) << endl;
    
        while ( current_node)
        {
            out << StringPadding(current_node->item.getName(), 30)
                << StringPadding(current_node->item.getLocation(), 10)
                << StringPadding(current_node->item.getRating(), 10)
                << StringPadding(current_node->item.getAcres(), 10)
                << endl;
            current_node = current_node->nextByName;
        }
    }
    

提交回复
热议问题