Convert MQTT Payload to String

Hello,

I am new to C++ and have a little problem.
I want to convert the MQTT Payload to a String.

char payloadString[length];
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
    payloadString[i] = (char)payload[i];
  }
}

This code has some ugly characters at the end…

ON⸮?

Where does the payload come from? Post full code (a MQTT Payload is the actual content of the message. MQTT is totally data-agnostic, it’s possible to send images, texts in any encoding, encrypted data and virtually every data in binary)

Would suggest you print also the hex value to see what these are

I want to convert the MQTT Payload to a String.

Why? The payload is an array of bytes. Bytes and chars are the same size, So, just put a NULL in payload at the length position, and treat the result as a string. If some function complains that payload isn't a char array, lie to the function.

   payload[length] = '\0';

   Serial.print("payload: [");
   Serial.print((char *)payload);
   Serial.println("]");

I use the PubSub 8266 Example.

@PaulS I wanna do this, because i want to check if the payload is "ON" or "OFF" ... or I'm thinking wrong? So i can do if (payload == "ON") ...

So i can do if (payload == “ON”) …

You can NOT do that. You can do:

  if(strcmp((char *)payload), "ON") == 0)

after you add a NULL to the proper place in payload, as I showed.

If that doesn’t work, it is because there are other bytes in the payload that are not ASCII characters.

There are string function that let you know if a string contains an other string, such as strstr().