Extra Eyes: String Concatenation

For the life of me, I cannot figure out why this code does not compile. I get “invalid operands of types ‘const char[3]’ and ‘const char[10]’ to binary ‘operator+’”. Looked around the forums for string concatenation, and couldn’t come up with anything that fixed the compilation error. Figure I must just be missing something simple. Help!

int photocell;
String content;

photocell = analogRead( PHOTOCELL_PIN );

content =
  "{ " +
    "\"light\": " + String( photocell ) +
  " }";


Operator precedence.

Concat them one section at a time.

1 Like

You could also do it with a char array instead of String using sprintf,

char content[20];

sprintf(content, "{ \"light\": %d }", photocell);
1 Like

I’d definetly go with @Ric’s advice, but if you do this

content = "{ \"light\": " + String( photocell ) + " }";

it builds.

The point is that there is no plus operator that can concatenate two char[] operands, which would be needed to do this "{ " + "\"light\": "

Thanks for the tips, everybody!

The JSON I am formatting is a few properties longer, so I was looking to break it out over multiple lines for readability. I was using sprintf but that got to be difficult to read.

Any comments on the SparkJSON library? Seems pretty popular, though the fact that it still carries the “Spark” label and hasn’t been touched in two years makes me question performance on modern Particle systems.

Thanks - K

You can also have a sprintf() split over multiple lines like this

char msg[256];

snprintf(msg, sizeof(msg), 
        "%d. this is the first line of my text\r\n"
        "%d. this is the second line of my text\r\n"
        "%d. this is the third line of my text\r\n"
        , 1, 2, 3);

And char[] is a lot safer to use IMHO.

But for your original intent you could also have written this

content =
  "{ "
    "\"light\": " + String( photocell ) +
  " }";

since adjacent string literals are stitched together by the compiler already without any need for a concat operation.

About the library, there is no hardware dependency in that library, so I wouldn’t expect anything to have changed fro m Spark Core to Particle devices in that regard.
One limitation I recently found seems to be that you can’t parse more than 15 key/value pairs in a given node (only tested for root tho’).


Thanks! I appreciate the insight to string handling! - K