Joining Text
The + operator can also join texts of type std::string. The result is a new text that you can store in a variable or print:
std::string firstName = "Anna";
std::string lastName = "Smith";
std::string fullName = firstName + " " + lastName;
std::cout << fullName << "\n";This prints:
Anna SmithJust like <<, + doesn't add any spaces. That's why there's " " between the first and last name: a text that contains only a space. Without it, you'd get AnnaSmith.
With +=, you add text to the end of a variable:
std::string message = "Hello";
message += ", Anna";
message += "!";
std::cout << message << "\n";This prints:
Hello, Anna!Typical mistakes:
- You can't join two texts in quotes with
+.std::string greeting = "Hello, " + "Anna";ends with the errorinvalid operands to binary expression ('const char[8]' and 'const char[5]'). A text in quotes isn't astd::stringon its own, and+can't work with two of them. So at least one side of+has to be astd::string, such as a variable:firstName + "!"works. +doesn't turn numbers into text. Whenpointsis anint,"Points: " + pointscompiles, but it prints nonsense, such as a piece of some other text from memory. AndfirstName + pointsends with the errorinvalid operands to binary expression. So print numbers with text using<<:std::cout << "Points: " << points;
Instructions
- 1
Create a variable
fullNameof typestd::string: with+, joinfirstName, a space andlastName. - 2
Print
fullName. The program should printAnna Smith. - 3
Below it, create a variable
greetingwith the value"Hello, ", and addfirstNameto it with+=. - 4
Add an exclamation mark to
greetingtoo, and print it on the next line. The program should print:Anna Smith Hello, Anna!