【问题标题】:fmt std::string displayed as numbersfmt std::string 显示为数字
【发布时间】:2019-11-27 17:10:56
【问题描述】:

我尝试格式化一个将显示在控制台中的简单字符串

    long long duration = end - start;

    double ms = static_cast<double>(duration) * 0.001;

    std::string resoult = fmt::format("{} => Duration: {} micro, {} ms", m_Info.c_str(), duration, ms);
    AE_TRACE(resoult);

m_Info 是 std::string,duration 是 long long,ms 是 double。 结果如下所示: -9891888000000.0 =&gt; Duration: 49172 micro, 412316861 ms

std::string 显示为随机数,ms 应该是 49,172。

我试过了 "{:s} =&gt; Duration: {:d} micro, {:f} ms"

但这导致fmt::format_errror。我在同一个项目的其他文件中使用了同一个库,并没有出现此类错误。

编辑

我在同一部分代码中使用了其他一些 fmt 函数

    long long duration = end - start;

    double ms = duration * 0.001;

    std::string test = "test";

    fmt::memory_buffer temp;

    fmt::format_to(temp, "{} {} {}", test, duration, ms);

    AE_TRACE(fmt::format("{} {} {}", test, duration, ms));
    AE_TRACE(temp.data());
    AE_TRACE("{} {} {}"_format(test, duration, ms));
    AE_TRACE(test);

在所有这些std::stringdouble 中都显示为一些随机数。 最后一个函数正确打印了未格式化的std::string,当我尝试使用long longdouble 时也发生了同样的情况。

【问题讨论】:

标签: c++ formatting fmt


【解决方案1】:

您没有提供足够的信息来调试它,但可能是您的 fmtlib 副本和 spdlog 中的副本不喜欢对方。 spdlog 提供了一个 cmake 配置变量来防止这种情况发生,即(来自我的 cmake 文件)

set(SPDLOG_FMT_EXTERNAL ON CACHE BOOL "Use common fmtlib")

你可能想试试这个。

【讨论】:

    【解决方案2】:

    我找到了原因。这是因为我在fmt之前包含了spdlog

    之前

    #include "../log/Log.h"
    #include "fmt/format.h"
    

    之后

    #include "fmt/format.h"
    #include "../log/Log.h"
    

    【讨论】:

    • 您不应该在代码中混用两个版本的 {fmt}。要么按照 tobi_s 的建议定义 SPDLOG_FMT_EXTERNAL,要么使用 spdlog 的版本。
    猜你喜欢
    • 2015-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    相关资源
    最近更新 更多