to_string
- C++ course
- Beginner
- Lesson 90/116
- 5 min
Learn number-to-string conversion with to_string.
to_string: number to string
When you need to turn a number into a string, you use the to_string function. It takes numeric types like int, double, long and returns a std::string.
int score = 95;
string result = to_string(score);Here the result string becomes "95". to_string is especially useful when you want to combine a number with a label and print it; it joins easily with + because both sides are now string.
Combining numbers with strings
You cannot add a number directly to a string with +; the compiler rejects it. You must first convert the number with to_string.
int age = 18;
string message = "Age: " + to_string(age);Here the message string becomes "Age: 18". This pattern is the shortest way to show values like age, score or step count to the user in plain text. cout can also print numbers directly with <<; but if you want to keep the string in a variable, to_string is required.
Practice Combine the score with a label
Define the variable int score = 87;. Use string message = "Score: " + to_string(score); to convert the number and join it with the label. Then print it with cout << message << endl;.
Starter code
#include <iostream>
#include <string>
using namespace std;
int main() {
int score = 87;
// use to_string to add the score to the "Score: " string and print it
return 0;
}Sample solution
#include <iostream>
#include <string>
using namespace std;
int main() {
int score = 87;
string message = "Score: " + to_string(score);
cout << message << endl;
return 0;
}Expected output
Score: 87
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does to_string(42) return?
- char '4'
- int value 42
- string "42" Correct answer
- double 42.0
Explanation: to_string returns a string; it becomes "42".
2 Fill in the blank: convert number to string
int step = 5;
string message = "Step: " + ____(step);
int step = 5;
string message = "Step: " + to_string(step);
Explanation: to_string converts the number so it can be joined.
3 Match each function with its purpose
| Term | Meaning |
|---|---|
to_string |
Number to string |
stoi |
String to integer |
stod |
String to double |