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

C++20 format()能否搭配原始字符串字面量?GCC14报错解析

在C++20 std::format中使用原始字符串字面量的正确方式

可以在C++20的std::format()中使用原始字符串字面量,但你的代码因未正确处理格式字符串中的字面量大括号导致编译错误。

错误原因分析

你试图生成JSON格式的字符串,但JSON结构中的{和}没有按照std::format的规则转义。std::format会将格式字符串中的单个{视为格式占位符的起始,当它遇到{"id":中的{时,会尝试解析后续内容为参数ID或格式说明,但"id":并非合法的格式语法,因此触发了__invalid_arg_id_in_format_string错误。

修正后的代码

#include <format>
#include <stdio.h>
#include <string>
using namespace std;

int main(){
    int id=6, sigma_edge_distance=9, width=6, height=9, total=6;
    // JSON的{用{{转义,}用}}转义,格式占位符{}保持不变
    string buffer = format(R"({{"id":{}, "sigma_edge_distance":{}, "width":{}, "height":{}, "total":{}}})",
                id, sigma_edge_distance, width, height, total);
    printf("%s", buffer.c_str());
    return 0;
}

关键说明

  • 原始字符串字面量的优势是无需转义双引号("),但不会改变std::format的格式解析规则。
  • 在std::format的格式字符串中,若要输出字面量的{或},必须写成双大括号{{或}}——无论使用普通字符串还是原始字符串,这一规则都适用。

内容的提问来源于stack exchange,提问作者Ludovic Aubert

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 09:02:43