Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying float values into char array

I'm writing a TCP socket in C to send location data for a project I'm working on.

So far, everything works, but I'm struggling with this seemingly simply problem. I'm trying to build a JSON String that will be sent over the socket. I have a character array (representative of the String) json defined as:

char json[1024];

With a method prototype:

const char* build_json(void);

And method body:

const char* build_json(void) {
    strcpy(json, "{");
    strcat(json, "\"latitude\":");
    sprintf(json, "%0.5f", latitude);
    strcat(json, "}");
    return json;
}

I know that latitude is defined correctly and should be a float of approximately 5 decimal places.

But when I call build_json();, 38.925034} is the only thing that is returned. Why is this the case? It appears that the call to sprintf is overwriting what's already been written in json.

Thanks for your help!

like image 575
James Taylor Avatar asked May 11 '26 08:05

James Taylor


2 Answers

sprintf will not append to your string; rather, it will overwrite whatever is there. You could do this:

sprintf(json + strlen(json), "%0.5f", 213.33f);

But, to be honest, this is a much better solution:

sprintf(json, "{\"latitude\":%0.5f}", location);

And this solution is still better:

snprintf(json, sizeof(json), "{\"latitude\":%0.5f}", location);
json[sizeof(json) - 1] = '\0';

as long as json is an array visible to the function that calls snprintf, i.e. allocated in that function on the stack, or globally. If it's a char* that you pass to the function, this will fail miserably, so beware.

like image 129
user4520 Avatar answered May 12 '26 21:05

user4520


You had better to do this only with sprintf to avoid multiple operations.

const char* build_json(void) {
    sprintf(json, "{\"latitude\":%0.5f}", latitude);
    return json;
}

Moreover if you are writing network code, you had better to allocate your string in your function and not relying on global. Often, network code are done in a multi-thread way.

like image 34
TrapII Avatar answered May 12 '26 22:05

TrapII



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!