首页 > 解决方案 > 无法使用 {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;
}

标签: c++fmt

解决方案


前面:的数字用于计算参数。
0:是第一个,1:第二个......
如果你之前没有放任何东西,:那么参数将被按顺序考虑。
您不能在相同的格式字符串中混合一些{}带有参数计数器和其他没有这样的参数计数器。


推荐阅读