如何格式化此输出C ++

时间:2016-03-25 18:01:40

标签: c++ format iomanip

我有一个包含一个单词和一组整数作为值的地图。 我想输出左对齐的单词,然后输出排列的列中的整数值。我认为这会起作用,但似乎输出非常糟糕。

我如何调整此值以使数字列彼此对齐并且它们之间有相当大的空间?

for (auto cbegin = ident_map.begin(); cbegin != ident_map.end(); cbegin++) {
    outFile << left << (*cbegin).first << setw(10);
    for (set<int>::iterator setITR = (*cbegin).second.begin(); setITR != (*cbegin).second.end(); setITR++) {
        outFile << right << *setITR << setw(4);
    }
    outFile << endl;
}

我认为这应该输出正确但看起来像这样:

BinarySearchTree         4
Key          4  27
OrderedPair         1   4   8  14
T            4
erase        27
first         7  13
insert         1   4
key         27
kvpair         1   4
map_iterator         1   3   8  14
mitr         3   7   8  13  14
result         4   6   7  13
result2         8   9  14  15
second         6
t            4
value_type         1

2 个答案:

答案 0 :(得分:0)

尝试Boost.Format

这是一个与您想要做的精神相似的玩具示例。 %|30t|%|50t|格式化工具可确保您的数字分别在第30列和第50列左对齐。

#include <iostream>
#include <boost/format.hpp>

int main(int argc, char *argv[]) {
    std::cout << "0         1         2         3         4         5         " << std::endl;
    std::cout << "012345678901234567890123456789012345678901234567890123456789" << std::endl;

    for (int i = 0; i < 10; i++) {

        // Set up the format to have 3 variables with vars 2 and 3 at
        // columns 30 and 50 respectively.
        boost::format fmt("string %1%: %|30t|%2% %|50t|%3%");

        // Append values we want to print
        fmt = fmt % i;
        for (int j = 0; j < 2; j++) {
            fmt = fmt % rand();
        }

        // Write to std::cout
        std::cout << fmt << std::endl;

        // Or save as a string...
        std::string s = fmt.str();
    }
    return 0;
}

运行时,产生:

$ ./a.out 
0         1         2         3         4         5         
012345678901234567890123456789012345678901234567890123456789
string 0:                     16807               282475249
string 1:                     1622650073          984943658
string 2:                     1144108930          470211272
string 3:                     101027544           1457850878
string 4:                     1458777923          2007237709
string 5:                     823564440           1115438165
string 6:                     1784484492          74243042
string 7:                     114807987           1137522503
string 8:                     1441282327          16531729
string 9:                     823378840           143542612

答案 1 :(得分:-1)

如何尝试使用\t代替setw()\t是标签特殊字符。这将为您的格式创造奇迹,因为您可以找出每行的第一个位置的标签数量,然后就像您想要的格式一样简单,效果很好因为标签是统一的大小