Search⌘ K
AI Features

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.

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 string to 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:

C++
#include <iostream>
#include <string> // Allows use of string type
using namespace std;
int main() {
string name = "Alex"; // Stores the name in a string variable
cout << "Hello, " << name << "!" << endl; // Prints greeting with the name
return 0;
}
Breakdown of a string in C++
Breakdown of a string in C++

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:

C++
#include <iostream>
#include <string>
using namespace std;
int main() {
int score = 95;
string result = "Your score is " + to_string(score); // Converts score to string and combines it with message
cout << result << endl; // Prints the final message
return 0;
}

You have used to_string() to convert an int into a string.

to_string ( ) function in C++
to_string ( ) function in C++

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:

C++
#include <iostream>
#include <string>
using namespace std;
int main() {
string message = "Loading"; // Stores initial message
message = message + "... done!"; // Adds more text to the message
cout << message << endl; // Prints the full message
return 0;
}

You have edited and updated a string.

String concatenation in C++
String concatenation in C++

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 existing message.

The += operator is called the compound assignment operator. It works for numbers too, not just strings.