Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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

  1. 1

    Create a variable fullName of type std::string: with +, join firstName, a space and lastName.

  2. 2

    Print fullName. The program should print Anna Smith.

  3. 3

    Below it, create a variable greeting with the value "Hello, ", and add firstName to it with +=.

  4. 4

    Add an exclamation mark to greeting too, and print it on the next line. The program should print:

    Anna Smith
    Hello, Anna!
Back

9/11

  1. 1. Creating Variables
  2. 2. Printing Variables
  3. 3. Initialization and Assignment
  4. 4. Data Types
  5. 5. Arithmetic
  6. 6. Integer Division
  7. 7. Quiz: Integer Division
  8. 8. Updating Variables
  9. 9. Joining Text
  10. 10. Quiz: Joining Text
  11. 11. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.