Step 3
Working with text
Join strings, ask a string its length and build readable messages with std::format.
Strings
A std::string holds text. Join strings with +:
std::string color = "red";
std::string name = color + " ball"; // "red ball"
+ joins strings to strings, not numbers: "x = " + 0.5 won't compile. std::to_string(0.5) turns a double into text, but always with six decimals: "0.500000".
Strings come with member functions, called with a dot after the variable. color.size() is the number of characters, 3, and color[0] is its first character, 'r'. A single character goes in single quotes and has its own type, char.
std::format
Joining with + gets clumsy fast. std::format, from #include <format>, writes values into a pattern: each {} is replaced by the next value.
double x = 0.1234;
std::string msg = std::format("The {} ball is at x = {} m", color, x);
// The red ball is at x = 0.1234 m
Put a format after a colon inside the braces to control how a number looks. {:.2f} means "2 digits after the decimal point":
std::cout << std::format("x = {:.2f} m", x) << "\n"; // x = 0.12 m
You'll use this all the time to print positions and sensor readings without a wall of digits. Some later lessons use the older std::printf("x = %.2f m\n", x), which does the same job.
Your task
The starter has a ball's color and its position x in metres.
- Print
The word red has 3 letters, usingcolor.size()for the 3. - Set
labelto text likered ball at x = 0.12 m, withxrounded to 2 decimal places. Usestd::format. - Print
label.
The grader reads color and x from the first two lines the starter prints, so keep those.