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 Smith

Just 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 error invalid operands to binary expression ('const char[8]' and 'const char[5]'). A text in quotes isn't a std::string on its own, and + can't work with two of them. So at least one side of + has to be a std::string, such as a variable: firstName + "!" works.
  • + doesn't turn numbers into text. When points is an int, "Points: " + points compiles, but it prints nonsense, such as a piece of some other text from memory. And firstName + points ends with the error invalid 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

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

8/9