【发布时间】:2021-07-28 12:40:42
【问题描述】:
我正在尝试格式化 JSON 字符串以避免使用 fmt::format,因为 json 确实包含 {0} 并且 fmt 无法区分 JSON 的括号和格式说明符 {0} 的括号。如果使用 fmt::format 我得到以下错误:
terminate called after throwing an instance of 'fmt::v7::format_error'
what(): invalid format string
Aborted (core dumped)
这就是我尝试使用fmt::sprintf 的原因。我找不到对 c++ 有用的解决方案,但我看到了一个 Golang 解决方案,但它不起作用,即:fmt.Sprintf("%[2]d %[1]d\n", 11, 22)(当然我已将其更改为 fmt::sprintf)。
如何使用 fmt::sprintf 为格式说明符提供参数索引?
提前致谢。
编辑:
JSON 不是我生成的,而是 sqlite 生成的。该 json 包含一个 {0},由于外部 JSON 大括号,它没有被格式化。
【问题讨论】:
-
because i cannot escape all为什么不呢?I need the same thing but with fmt::sprintf()我非常怀疑你需要那个,无论如何,here's the docs 和 her's posix docs 而你正在搜索%1d。 -
@KamilCuk 仔细阅读问题(包括错误信息),你就会明白为什么了。
-
我不明白,它如何改变任何东西?所以逃离他们。 *您正在搜索
%1$d。 -
@KamilCuk: fmt 使用
{{来转义大括号,而不是\{... -
该问题与 fmt::format 或 fmt::sprintf 无关,而是与使用相同令牌的 JSON 和 FMT 有关。我认为你不能通过使用 fmt::sprintf 轻松解决这个问题。 JSON 解析器会尝试解析
{0},就像 FMT 会尝试解析{"iq"....}。