c++ - 无法使用 {fmt} 库在一个字符串中格式化两个浮点数
问题描述
我刚开始{fmt}
在我的应用程序中使用该库,发现由于程序崩溃,我无法使用该库来格式化具有不同位数的两个浮点数。
经过一些实验,我意识到它实际上有点糟糕,因为在我格式化任何浮点数后我无法格式化任何东西{0:.0f}
(或者0:.2f
,就此而言)。
对我来说违反直觉的代码示例:
#include <fmt\core.h>
#include <iostream>
int main()
{
std::cout << fmt::format("{} , {}\n", 3.14, 10.0); // Prints out '3.14, 10.0'
//std::cout << fmt::format("{0:.0f} , {}\n", 3.14, 10.0); // - ERROR: fmt::v6::format_error at memory location
std::cout << fmt::format("{0:.0f} , {0:.0f}\n", 3.14, 10.0); // - WRONG RESULT: Prints out '3, 3'
std::cout << fmt::format("{0:.0f} , {:d}\n", 3.14, 10); // ERROR: fmt::v6::format_error at memory location
//std::cout << fmt::format("{:s}, {:s}", fmt::format("{0:.2f}", 3.14), fmt::format("{:0:.1f}", 10.0)); // EVEN THIS DOESN'T WORK
// This is the only way I found of getting the output I want:
std::string a = fmt::format("{0:.2f}", 3.14);
std::string b = fmt::format("{0:.1f}", 10.0);
std::cout << fmt::format("{:s}, {:s}", a, b);
return 0;
}
解决方案
前面:
的数字用于计算参数。
0:
是第一个,1:
第二个......
如果你之前没有放任何东西,:
那么参数将被按顺序考虑。
您不能在相同的格式字符串中混合一些{}
带有参数计数器和其他没有这样的参数计数器。
推荐阅读
- python-3.x - 我如何在python中打印出一个数字三角形?不允许使用任何字符串。只有算术运算
- freeradius - 如何在 freeRADIUS 上为 EAP-TTLS 添加新的子方法
- flutter - 如何从 textfromfield 中保存值并将其传递回页面?
- javascript - 用 sinon 存根,用 chai 测试
- angular - 带有条件和空对象的补丁值
- c# - 需要签署一个 C# .exe
- python - 使用正则表达式捕获德语日期格式
- typescript - 如何使用 Jest 测试静态方法中的方法?
- windows - Docker for Windows 会干扰 VMware 吗?
- vba - Selenium VBA自动化Java脚本错误