假设我有一个 char 变量和一个整数变量。我想在输出它们时将它们视为一个变量(例如:B6、A2、C10 等)
我想在 4 个空格中正确地证明这两个变量的正确性,但我一生都无法弄清楚如何做到这一点。(我想要下划线为空格的 _A10 和 __A6)
是否可以在 C++ 中做到这一点?
这是一个没有 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
使用 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|