Serial.printlnf - can't handle Strings?

Maybe I need the sleep, but can anyone verify this with a 0.4.6 Photon?

Test 1: (works fine)

Serial.printlnf("The %s jumped over the moon", "cow!");

Test 2: (compile throws a ‘non-trivially-copyable type’ error if a String variable is used)

String s = "cow";
Serial.printlnf("The %s jumped over the moon", s);

All other printf specifiers seem to work. Except for Strings.

Any ideas?

Try this

  String s = "cow";
  Serial.printlnf("The %s jumped over the moon", s.c_str());

"%s" expects a C string (char*) as source and not a String object. By use of c_str() your String object will hand you back a (char*).
This is what the error message is telling you - less trivially worded tho’ :wink:

Maybe at some point there will be an overload for the cast operators in the String class, but for now use this.

3 Likes

Thanks @ScruffR, c_str() did the trick.

I expected %s to take a String, and not a C string. The Serial.printf() documentation threw me off, as it used Time.timeStr() as an example. The Time.timeStr() documentation in turn, however states that Time.timeStr() returns a String.

…and, also learning to be more careful not to confuse C strings with Strings…

2 Likes

Sorry about that - I’ve fixed up the documentation accordingly. I was in a pinch and assumed the implicit conversion operator would have worked, but clearly not… :wink:

2 Likes