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
Create a variable fullName of type std::string: with +, join firstName, a space and lastName.
Print fullName. The program should print Anna Smith.
Below it, create a variable greeting with the value "Hello, ", and add firstName to it with +=.
Add an exclamation mark to greeting too, and print it on the next line. The program should print:
Anna Smith
Hello, Anna!Start programming for free
8/9