对齐列

时间:2017-09-26 20:48:52

标签: c++ alignment setw

对于我的实验室,我们需要在声明值的陈述后的列中显示输出值。

我需要的例子。

Amount of adult tickets:                      16
Amount of children tickets:                   12
Revenue from ticket sales:                    $140.22

我正在尝试使用像

这样的setw
cout << "Amount of adult tickets: " << setw(15) << ticketsAdult` << endl;
cout << "Amount of children tickets: " << setw(15) < ticketsChildren << endl;

我假设使用setw是错误的,或者我使用它是错误的,因为它通常导致类似

Amount of adult tickets:                    16
Amount of children tickets:                    12

我可以使用什么来使右边的值全部对齐,就像它们在示例中所做的那样,无论&#34;数量的长度如何...&#34;每个人之前的陈述?

2 个答案:

答案 0 :(得分:0)

看起来也有左右对齐。除此之外,它看起来很痛苦。

C++ iomanip Alignment

答案 1 :(得分:0)

将所有内容结合在一起

#include <iostream>
#include <iomanip>

int main()
{
    int ticketsAdult = 16;
    int ticketsChildren = 12;
    double rev =140.22;
    std::cout << std::setw(35) << std::left << "Amount of adult tickets: " <<  ticketsAdult <<  '\n';
    std::cout << std::setw(35) << std::left << "Amount of children tickets: " <<   ticketsChildren <<  '\n';
    std::cout << std::setw(35) << std::left << "Revenue from ticket sales: " <<   '$' << rev <<  '\n';
    return 0;
}