如何将结构体转换为字符串?

Ahm*_*ed 1 c++

我有以下结构:

typedef struct {
   float battery;
   float other;
   float humidity;
} rtcStore;

rtcStore rtcMem;
Run Code Online (Sandbox Code Playgroud)

我需要将结构中存储的数据发送到 thingspeak.com。但是,要发送数据,我需要将结构转换为字符串。谁能告诉我该怎么做?如果用C语言完成的话会更有帮助。

Sto*_*ogy 5

您可以使用 snprintf ( https://linux.die.net/man/3/snprintf ),如下所示:

char buffer[100];
snprintf(buffer, 100, "%.4f %.4f %.4f", rtcMem.battery, rtcMem.other, rtcMem.humidity)
Run Code Online (Sandbox Code Playgroud)

这将确保您的消息不会超过 100 个字符。查看文档。您还可以检查 snprintf 的返回值以确保一切正常。请参阅文档中的示例。

另一方面,您可以使用strtok解析字符串以提取字段并使用字符串到 float 转换器(如strtof )