1

I'm trying to combine two strings (strings/int) together with text in below code:

int foo = String((char*)payload).indexOf(' ');
int message1; 
int message2; 

message1 = String((char*)payload).substring(0, foo).toInt(); 
Serial.print(message1); // Returns 1

message2 = String((char*)payload).substring(foo + 1, length).toInt();
Serial.print(message2); // Returns 0

client.publish(msg, String(message1 + " " + message2).c_str(), true);
// published value: 1 0

Instead of publishing "1 0" its publishing some weird values, what am i missing?

  • message1 + " " + message2? you know what operator + does on int – Juraj Jan 17 '19 at 10:29
  • What type is payload? Is it a dynamically allocated char array? – Filip Franik Jan 17 '19 at 15:14
2

I wouldn't use the String class, but instead use the C functions to concatenate strings (like strcat, strncat).

You can use the itoa function to convert an integer to a string, see:

https://stackoverflow.com/questions/9655202/how-to-convert-integer-to-string-in-c

Or use the sprintf function.

These are all standard C functions which gives you complete control of the buffer sizes to use. Handy because the Arduino Uno has just 2 KB.

|improve this answer|||||
-1

After spending a good time on searching for an easy understandable formula, I found that i came across this question already in the past and saved the solution in other sketch (attaching it here for the next time!).

Below was the solution that worked now and then perfectly:

int foo = String((char*)payload).indexOf(' ');
int message1; 
int message2; 

message1 = String((char*)payload).substring(0, foo).toInt(); 
Serial.print(message1); // Returns 1

message2 = String((char*)payload).substring(foo + 1, length).toInt();
Serial.print(message2); // Returns 0

char combinedval[40];
strcpy(combinedval, String(message1).c_str());
strcat(combinedval, " ");
strcat(combinedval, String(message2).c_str());
client.publish(msg, combinedval, true);

// published value: 1 0

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.