c - char * 中的变量占位符

标签 c

我有以下 C 示例:

char *message;
char *name = "John";
int age = 100;

message = "Hello, I am John, age 100"; 

如何将nameage作为message的参数?

伪代码message = "你好,我是{name},年龄{age}"

更新

我从评论中尝试了以下示例:

char *body = "{ \"capabilities\": {},\"desiredCapabilities\": {}}";
int content_length = sizeof(body);

char *format = "POST /session HTTP/1.1\r\nContent-Type: application/json\r\nContent-Length:%d\r\n\r\n%s";
int len = snprintf(NULL, 0, format, content_length, body);
char *message = malloc(len + 1);
snprintf(message, len + 1, format, content_length, body);

但我在 char *message = malloc(len + 1); 处遇到错误:

错误:从“void*”到“char*”的无效转换 [-fpermissive]|

最佳答案

您可以使用 snprintf 执行此操作。这与 printf 类似,但将结果放入字符串而不是将其写入 stdout

char message[100];
snprintf(message, sizeof(message), "Hello, I am %s, age %d", name, age);

请注意,此示例使用固定大小的缓冲区。如果你想动态分配空间,你可以这样做:

const char *format = "Hello, I am %s, age %d";
int len = strlen(format) + strlen(name) + sizeof(age)*3 + 1;
char *message = malloc(len);
snprintf(message, len, "Hello, I am %s, age %d", name, age);
// ...
free(message);

这为格式字符串、每个参数和终止空字节留出空间。

另一种获得所需长度的方法是调用 snprintf 两次,第一次使用 NULL 作为字符串,0 作为大小。返回值是结果字符串的长度:

const char *format = "Hello, I am %s, age %d";
int len = snprintf(NULL, 0, "Hello, I am %s, age %d", name, age);
char *message = malloc(len + 1);
snprintf(message, len + 1, "Hello, I am %s, age %d", name, age);
// ...
free(message);

关于更新代码中的错误,您显然使用的是 C++ 编译器而不是 C 编译器。如果您正在编写 C,请使用 C 编译器。

关于c - char * 中的变量占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45698666/

相关文章:

c - 为指向指针数组的指针分配空间

Android alsa snd_pcm_open default no such file o 目录

c - 二叉搜索树插入(C)

c - 更新 select() 调用中的超时值

c - 如果线程在调用 pthread_mutex_lock() 时没有成功,会发生什么情况?

采用 const 二维数组的 C 函数

c - 编译 C 文件时出现有趣的错误消息

c - 在 C 中打印数组元素的地址时出错

c - 为什么我的 OpenMP 实现比单线程实现慢? (跟进)

c - 字符串中的大写字符无法转换为小写字符,并且减去它们的 ASCII 值不会使它们出现在字母索引中