Work with the Text
Explore how to use the string data type in C++ to store, update, and combine text. Learn string concatenation, converting integers to strings, and printing output with customized messages.
We'll cover the following...
So far, we’ve worked with numbers, but C++ can handle text too. In this lesson, you’ll learn how to use string to store and manipulate sentences and words.
Goal
You’ll aim to:
Use
stringto hold text.Combine strings with other variables.
Convert an int to a string using
to_string().Print personalized messages.
Create a string
Let’s turn our "Mr. A" example into something more complete, like "Alex" instead.
We’ll declare a variable using the string data type to store a full name, instead of just a single character:
You’ve created and used your first string!
Combine strings and numbers
We can also convert an int to a string in C++ using to_string(), then combine numbers and strings and print them together:
You have used to_string() to convert an int into a string.
Update a string
Just like an int variable, we can also update a string variable. We can use the ‘+’ sign to combine strings, a process called string concatenation:
You have edited and updated a string.
Strings are flexible and editable.
You can use
+=operator for string concatenation, just like this:message += "... done!";This is the same as writing:
message = message + "... done!";Both lines add
"... done!"to the end of the existingmessage.The
+=operator is called the compound assignment operator. It works for numbers too, not just strings.