gpt4 book ai didi

c - snprintf 在被复制的字符串中使用格式说明符

转载 作者:行者123 更新时间:2023-12-02 07:58:06 30 4
gpt4 key购买 nike

我创建了以下程序:

#include<stdio.h>
#include<stdlib.h>

#define TESTER "name=%s "

int main(){
char *x;
x = malloc(100);
snprintf(x, 100, "Heyaa tester %s", TESTER, "hello");
printf("%s", x);
free(x)
return 0;
}

我基本上是在尝试让输出类似于 - “Hey tester name=hello”,但是,它似乎如下所示:

Heyaa tester name=%s

我是否需要首先将 hello 附加到宏,然后对 malloc 变量执行 snprintf

谢谢。

最佳答案

您需要将宏作为 snprintf() 的格式说明符的一部分包含在内它扩展到 "name=%s "在预处理器本身和连接字符串时 "Heyaa tester name=%s"被 build 。你在 OP 中拥有的是 name=%s作为将经历 %s 的文字字符串snprintf() 的格式化处理

snprintf(x, 100, "Heyaa tester " TESTER, "hello");

如果您在编译器中启用了额外的警告标志作为 printf(),您最初的尝试应该被视为可疑。会发出警告太多参数但找不到足够的说明符([-Wformat-extra-args] 与 gcc)。

并且作为一种更好的编码习惯,始终清理程序动态分配的内存,而不是让操作系统这样做,并且始终使用额外的警告标志编译您的程序。

关于c - snprintf 在被复制的字符串中使用格式说明符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60885147/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com