You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++ Fmt库中正确使用命名参数?代码报错求助

关于fmt库运行时宽度格式化的异常问题

问题重现

代码示例:

#include <string>
#include <vector>

#include <fmt/core.h>
#include <fmt/format.h>

int main()
{
   std::vector<std::string> lines =
   {
      "line 1 - xxxxxxxx",
      "line 2 - xxxxxxxx",
      "line 3 - xxxxxxxx",
      "line 4 - xxxxxxxx",
   };

   const std::size_t width = 3;

   for (std::size_t i = 0; i < lines.size(); ++i)
   {
      const auto& line = lines[i];
      fmt::println("{:0{width}} {}",
                   i, fmt::arg("width",width),
                   line);
   }

   return 0;
}

期望输出:

000 line 1 - xxxxxxxx
001 line 2 - xxxxxxxx
002 line 3 - xxxxxxxx
003 line 4 - xxxxxxxx

实际运行抛出异常:

Program returned: 139
libc++abi: terminating due to uncaught exception of type fmt::v11::format_error: cannot switch from manual to automatic argument indexing
Program terminated with signal: SIGSEGV

问题原因

异常信息明确指出:不能从手动参数索引切换到自动参数索引。代码混合了两种参数传递方式:

  • 使用fmt::arg("width", width)传递命名参数(手动索引方式)
  • 第二个{}占位符依赖自动位置索引(对应第三个参数line)

fmt库不允许在同一条格式化语句中混合使用命名/手动索引参数和自动位置索引参数,因此触发了格式化错误。

修复方案

核心是统一参数索引方式,以下两种方式均可:

方式一:统一使用位置参数

将宽度作为位置参数传入,格式化字符串中用位置占位符表示宽度:

#include <string>
#include <vector>

#include <fmt/core.h>
#include <fmt/format.h>

int main()
{
   std::vector<std::string> lines =
   {
      "line 1 - xxxxxxxx",
      "line 2 - xxxxxxxx",
      "line 3 - xxxxxxxx",
      "line 4 - xxxxxxxx",
   };

   const std::size_t width = 3;

   for (std::size_t i = 0; i < lines.size(); ++i)
   {
      const auto& line = lines[i];
      // 用{}表示宽度参数的位置,对应第二个参数width
      fmt::println("{:0{}} {}", i, width, line);
   }

   return 0;
}

方式二:统一使用命名参数

将所有参数都改为命名参数,格式化字符串中对应使用命名占位符:

#include <string>
#include <vector>

#include <fmt/core.h>
#include <fmt/format.h>

int main()
{
   std::vector<std::string> lines =
   {
      "line 1 - xxxxxxxx",
      "line 2 - xxxxxxxx",
      "line 3 - xxxxxxxx",
      "line 4 - xxxxxxxx",
   };

   const std::size_t width = 3;

   for (std::size_t i = 0; i < lines.size(); ++i)
   {
      const auto& line = lines[i];
      fmt::println("{index:0{width}} {content}",
                   fmt::arg("index", i),
                   fmt::arg("width", width),
                   fmt::arg("content", line));
   }

   return 0;
}

两种方式都能正常输出期望的格式化结果。

内容的提问来源于stack exchange,提问作者Penny Dreudter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 23:45:06