右对齐C ++中的两个变量(我想将它们视为一个变量)

时间:2017-04-26 03:48:12

标签: c++ iomanip setw

假设我有一个char变量和一个整数变量。我想在输出时将它们视为一个变量(例如:B6,A2,C10等)

我想在4个空格的插槽中对这两个变量进行正确的证明,但我不能为我的生活找出如何做到这一点。 (我想要_A10和__A6,其中下划线是空格)

是否可以在C ++中执行此操作?

2 个答案:

答案 0 :(得分:1)

这是一个没有Boost依赖的解决方案。将整数转换为字符串,与char连接,并使用std::setw设置流宽度。例如:

#include <iostream>
#include <iomanip>
int main(void)
{
    char a = 'A', b = 'B';
    int ai = 10, bi = 6;
    std::cout << std::setw(4) << (a + std::to_string(ai)) << std::endl;
    std::cout << std::setw(4) << (b + std::to_string(bi)) << std::endl;
}

在我的机器上打印:

 A10
  B6

答案 1 :(得分:0)

使用Boost.Format将printf样式格式应用于C ++流。

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

int main()
{
  char c = 'A';
  int i = 10;
  std::cout << boost::format("|%4s|") % (c + std::to_string(i)) << '\n';
}

输出:

| A10|