如何使用snprintf输出JSON格式
时间: 2023-06-09 12:08:02 浏览: 237
snprintf:snprintf的独立实现
的数据?
您可以使用snprintf函数将数据格式化为JSON格式,并将其打印出来。下面是一个示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1024
int main() {
char buffer[BUFFER_SIZE];
int length = 0;
const char *name = "John";
int age = 30;
double height = 1.75;
length = snprintf(buffer, BUFFER_SIZE,
"{"
"\"name\": \"%s\","
"\"age\": %d,"
"\"height\": %f"
"}",
name, age, height);
if (length >= BUFFER_SIZE || length < 0) {
printf("Error: Snprintf failed.\n");
return EXIT_FAILURE;
}
printf("%s", buffer);
return EXIT_SUCCESS;
}
```
这段代码将输出以下JSON格式的字符串:
`{"name": "John", "age": 30, "height": 1.750000}`
您可以通过更改变量的值来测试该代码。
阅读全文