Strings: operator<< vs. String::formatted


#1

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 ?


#2

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

or

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


#3

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));

#4

or slightly simpler:

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

#5

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 ?


#6

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!)