是否可以像 Python 的 f-strings 那样在 C 中格式化字符串?

Is it possible to format strings in C like Python's f-strings?

在 Python 中可以使用 f 字符串方便地格式化字符串:

num = 12
print(f"num is {num}") # prints "num is 12"

在 C 中可以做这样的事情吗?或者类似的东西? 目前,要将变量添加到我正在使用此方法的输出:

int num = 12;
printf("num is %d", num);

这是在 C 中向打印语句添加变量的唯一方法吗?

正如 ForceBru 所说,您可以使用 sprintf(char *str, const char *format, ...),但您需要分配一个字符串来接收该结果:

int num =0;
char output_string[50];
sprintf(output_string,"num is %d", num);

现在output_string可以随意打印

{num}")

Is it possible to do something like this in C?

不,这是不可能的。 C语言是没有reflection的编程语言。在 C 中无法通过存储在字符串中的名称来查找变量。

另一方面,

Python 是一种解释性语言,其背后有一个完整的解释器实现,它跟踪所有变量名称和值,并允许在解释性语言本身内查询它。所以在 python 中使用字符串 "num" 你可以找到一个具有该名称的变量并查询它的值。

PS。 可能 具有许多宏和 C11 _Generic 功能,无需指定 %d printf 格式说明符并使 C 更接近 C++-ish std::cout << 函数重载 - 为此,您可能需要探索 my try at it with YIO library。但是,为此,建议只迁移到 C++ 或 Rust 或其他功能更全的编程语言。