Ahmed
Ahmed

Reputation: 61

How to convert structure to a string?

I have the following structure:

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

rtcStore rtcMem;

I need to send the data stored in the structure to thingspeak.com. However, to send the data I need to convert my structure to a string. Can anyone tell me how to do so? It will be more helpful if it's done in C.

Upvotes: 1

Views: 3536

Answers (2)

Stoogy
Stoogy

Reputation: 1351

You can use snprintf (https://linux.die.net/man/3/snprintf) as follow:

char buffer[100];
snprintf(buffer, 100, "%.4f %.4f %.4f", rtcMem.battery, rtcMem.other, rtcMem.humidity)

This will make sure that your message won't exceed 100 characters. Have a look at the documentation. You can also check the return value of snprintf to make sure everything went fine. See the example in the doc.

On the other side, you can parse the string using strtok to extract the fields and use a string to float convertor like strtof

Upvotes: 5

Use sprintf to convert it to a string.

Upvotes: 2

Related Questions