Snprint With String Values

Hello,
I am trying to use the newly released Microsoft Azure IOT library.
There is a line in the initial sketch which I have modified heavily that states.

    // replace the following line with your data sent to Azure IoTHub
    snprintf(buff, 128, "{\"topic\":\"iot\"}");

I have tried to replace this with

    snprintf(buff, 128, "{\"" + MQTTTopic + "\":\"" + MQTTPayload + "\"}");

Which is erroring on compilation.

error: cannot convert 'StringSumHelper' to 'const char*' for argument '3' to 'int snprintf(char*, size_t, const char*, ...)'

     snprintf(buff, 128, "{\"" + MQTTTopic + "\":\"" + MQTTPayload + "\"}");

                                                                                          ^

I have never used snprint before and I am wanting to insert string values (MQTTTopic & MQTTPayload).

Is there a better way to do this and can someone please help me here.

Thanks in advance
Shane Baldacchino

Hi
I'm not a software expert, but try it like this:

 snprintf(buff, 128, "{\" + MQTTTopic + \":\" + MQTTPayload + \"}");

The snprintf() function is used with C-strings (zero terminated character arrays).

Don't use it with String objects.

When contemplating the use of a new function, it is an outstandingly good idea to study the reference guide!

https://www.cplusplus.com/reference/cstdio/snprintf/

If you really want to use a String then just concat the data in a new string

String tempString;
tempString.reserve(60);
tempString = String("{\"") + MQTTTopic + String("\":”) + MQTTPayload + String("}");

And then your cString buffer you want to send is in

tempString.c_str()

@jremington
From reading it looks like it is expecting a fixed character string I need to read up more on this

@J-M-L - Thank-you, you helped me a few months ago and appreciate you working around my capabilities. Your code snippet works a charm. Thank-you!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.