我已经有一段时间没有在 StackOverflow 上发布任何问题了;我希望我或多或少记住了解决问题的适当方式(提前抱歉)。
\n我正在使用 C++ 流和 FMT 库,它提供了 C++23 打印的预览。当设置填充符来完成整数的显示宽度时,流很冷。例子:
\nconst int y = 730;\ncout << "y = " << setw(5) << y << endl;\ncout << "y = " << setfill('0') << setw(5) << y << endl;\ncout << "y = " << setfill('X') << setw(5) << y << endl;\ncout << "y = " << setfill('*') << setw(5) << y << endl;\nRun Code Online (Sandbox Code Playgroud)\n输出是
\ny = 730\ny = 00730\ny = XX730\ny = **730\nRun Code Online (Sandbox Code Playgroud)\n我试图使用 fmt::print\xe2\x80\x94 设置相同的填充符(包括“X”和“*”字符),例如:
\nprint("y = {:5d}\\n", y);\nprint("y = {:05d}\\n", y);\nRun Code Online (Sandbox Code Playgroud)\n好吧,我没有包含“X”和“*”。我并不是说使用随机字符作为填充符是个好主意;我只是很好奇,因为我需要向学生解释这些命令之间的区别。
\n提前致谢。\n维维安
\n该手册显示了整数格式说明符的以下语法:
format_spec ::= [[fill]align][sign]["#"]["0"][width]["." precision]["L"][type]
fill ::= <a character other than '{' or '}'>
align ::= "<" | ">" | "^"
Run Code Online (Sandbox Code Playgroud)
这format_spec是里面的部分{: }。
因此指定自定义填充符 ( fill) 还需要指定对齐方式(您想要>,即向右对齐):
fmt::print("y = {:X>5d}\n", y); // XX730
fmt::print("y = {:*>5d}\n", y); // **730
Run Code Online (Sandbox Code Playgroud)