Snprintf mixed types - FIXED

I have the following code:

char datasct[256];
snprintf(datasct, sizeof(datasct), "{\"ct1\": %f, \"humidity\": %d}", current_one, humidity);
Particle.publish("all_thingss", datasct, PRIVATE);

If I do one or the other both values come out right, the below works fine

char datasct[256];
snprintf(datasct, sizeof(datasct), "{\"humidity\": %d}", humidity);
Particle.publish("all_thingss", datasct, PRIVATE);

If I do both then the first one will be right and the second one is not. I assume its some kind of type issue but I’m not sure. Any ideas?

@Keaner, is humidity declared as a float? If it is, the snprintf statement should use %f and not %d for humidity.

no it is an int, it only gets messed up when the first one is say %f (the ct sensors) then switch to %d (humidity). Like above, if i do one or the other in the code, as opposed to two it works great.

so here is the response as an example

{“ct1”: 1.600000, “humidity”: 1952653947}

CT1 is right, but humidity should say 39

Its like the statement is trying to use %f as well for humidity instead of the %d specified. If i change both to %d then the ct is wrong and the humidity is right. Can I not mix?

@Keaner, did you try a constrained format for the float like %2.2f ?

Fixed!

This is what fixed it for me, fyi to others:

char datasct[256];
snprintf(datasct, sizeof(datasct), “{“ct1”: %f, “humidity”: %d}”, float(current_one), int(humidity));
Particle.publish(“all_thingss”, datasct, PRIVATE);

I had to add float and int again in the statement for some reason. I haven’t tried your answer @peekay123.

@Keaner, also try plain sprintf without the size constraint to see if the same issue persists.

ahh ok. i thought it was at 256 as that’s the most data iI could send. This is not my primary coding language, can you tell :slight_smile:

@Keaner, the limit is 255. However, the limit I was referring to was using sizeof() in snprintf(). The statement clearly will not exceed the limit the way it is right now. I just wanted to see if there is something odd about snprintf vs sprintf causing the problem.

ok, i’ll try that to just to see . thanks again for the help

1 Like

When asking such a question you should include the declaration of the respective variables too.
If your fix worked I’d assume the variables were not declared compatible to the format string.
Also check for name collisions/scope of variables.

1 Like

thanks for the input ScruffR. All my variables are global ones in this case.

It’s not clear why you’re having this problem; I can’t reproduce it. I tested this code, and it worked fine,

float current_one = 1.6;
int humidity = 39;


void setup() {}

void loop() {
    delay(5000);
    char datasct[256];
    snprintf(datasct, sizeof(datasct), "{\"ct1\": %f, \"humidity\": %d}", current_one, humidity);
    Particle.publish("all_thingss", datasct, PRIVATE);
    
}

The result was,

{“name”:“all_thingss”,“data”:"{“ct1”: 1.600000, “humidity”: 39}"

2 Likes