Strings: operator<< vs. String::formatted

Finding in the API doc for String::formatted::

I don’t like this method. I don’t use it myself, and I recommend avoiding it and using the operator<< methods or pretty much anything else instead.

Example code:

using String formatted:

String coordinates = String::formatted("Coordinates: %d x %d", x, y);

using operator<<:

String coordinates = "Coordinates: ";
operator<<(coordinates, x);
operator<<(coordinates, " x ");
operator<<(coordinates, y);

Can the operator<< method also be simplified to a one-liner ?

String coordinates (String ("Coordinates: ") + x + " x " + y);?

or

String coordinates; coordinates << "Coordinates: " << x << " x " << y;?

That’s better. :slight_smile:
Thanks.

(I should have posted this rather in Getting Started, sorry)

edit:
First suggestion doesn’t work.
But this does:

String coordinates(String("Coordinates: ") + String(x) + " x " + String(y));

or slightly simpler:

auto coordinates = "Coordinates: " + String(x) + " x " + String(y);
1 Like

auto specifier was unknown to me, I just looked it up, thanks.

Btw, is there a way or is it common to mark threads as “solved” or “resolved” here ?

You can modify the title if you want to, though there’s no standard practice on the forum. In this case there’s not much point. (It only really bothers us when people post nasty titles like “bug in juce class” which turn out not to be their own fault and not our bug!)