Question
I have the following C++ values:
std::string name = "John";
int age = 21;
How can I combine them into a single std::string so the result becomes "John21"?
Short Answer
By the end of this page, you will understand why a std::string cannot be directly concatenated with an int, how to convert numbers into strings in C++, and the most common ways to build combined text such as "John21". You will also see when to use std::to_string versus string streams in real code.
Concept
In C++, std::string stores text, while int stores a numeric value. Even though both can be displayed together when printing output, they are still different types.
When you concatenate strings, both sides of the + operator must be string-compatible values. An int is not automatically treated as a string during normal string concatenation, so this does not work:
std::string result = name + age; // error
To combine text and numbers into one string, you must first convert the number into text.
The most common modern way is:
std::string result = name + std::to_string(age);
This matters in real programming because many applications need to build strings dynamically:
- usernames like
"john21" - file names like
"report_2024" - log messages like
"Error code: 404" - API paths like
"/users/42"
Whenever text and numbers need to be combined, conversion is required.
Mental Model
Think of std::string as a box that can only hold text labels.
An int is a number object, not a text label. If you want to place the number into the text box, you must first turn it into text.
So instead of trying to mix:
"John"as text21as a number
You first convert 21 into "21", then combine:
"John" + "21" = "John21"
A good mental rule is:
If you want to store or combine something inside a string, convert it to text first.
Syntax and Examples
The most direct solution in modern C++ is std::to_string.
#include <string>
#include <iostream>
int main() {
std::string name = "John";
int age = 21;
std::string result = name + std::to_string(age);
std::cout << result << '\n';
}
Output:
John21
Why this works
nameis already astd::stringstd::to_string(age)converts21into the string"21"- now both parts are strings, so
+can concatenate them
Another example
#include <string>
{
std::string product = ;
id = ;
std::string code = product + std::(id);
std::cout << code << ;
}
Step by Step Execution
Consider this example:
#include <string>
#include <iostream>
int main() {
std::string name = "John";
int age = 21;
std::string result = name + std::to_string(age);
std::cout << result << '\n';
}
Step by step:
-
std::string name = "John";- Creates a string variable containing the text
"John".
- Creates a string variable containing the text
-
int age = 21;- Creates an integer variable containing the number
21.
- Creates an integer variable containing the number
-
std::to_string(age)- Converts the integer
21into the string"21".
- Converts the integer
-
name + std::to_string(age)
Real World Use Cases
Combining strings with numbers appears everywhere in C++ programs.
1. Building usernames or labels
std::string username = "user" + std::to_string(1001);
Result: "user1001"
2. Creating file names
std::string filename = "report_" + std::to_string(2024) + ".txt";
Result: "report_2024.txt"
3. Logging
std::string message = "Request failed with code " + std::to_string(404);
4. API or route construction
std::string path = "/users/" + std::to_string(42);
5. Game development
std::string levelName = "Level " + std::to_string(3);
These patterns are common whenever numbers must appear as readable text.
Real Codebase Usage
In real projects, developers often use a few common patterns when mixing strings and numbers.
Using std::to_string for simple cases
For short, readable concatenation:
std::string key = "item_" + std::to_string(id);
This is the most common choice for straightforward cases.
Using streams when building larger messages
std::ostringstream oss;
oss << "User " << userId << " has score " << score;
std::string message = oss.str();
This is useful when:
- combining many values
- formatting more complex text
- appending different data types in sequence
Validation before building strings
Developers often validate values before converting them:
if (age < 0) {
return "Invalid age";
}
return name + std::to_string(age);
This is an example of a guard clause: check bad input early, then continue with the normal logic.
Configuration and identifiers
Strings with numbers are commonly used for:
Common Mistakes
Here are common beginner mistakes when concatenating strings and integers in C++.
Mistake 1: Adding a string and an int directly
std::string result = name + age; // error
Why it fails:
nameis textageis a number- C++ does not automatically convert the
inttostd::stringhere
Fix:
std::string result = name + std::to_string(age);
Mistake 2: Forgetting the correct header
std::string needs:
#include <string>
If you use streams, you also need:
#include <sstream>
Mistake 3: Confusing output streaming with string concatenation
This works for printing:
Comparisons
Here is how common approaches compare.
| Approach | Example | Best for | Notes |
|---|---|---|---|
std::to_string | name + std::to_string(age) | Simple concatenation | Clear and modern |
std::ostringstream | oss << name << age | Complex string building | Flexible for many values |
std::cout << | std::cout << name << age | Printing only | Does not create a std::string |
| C-style formatting | sprintf(...) |
Cheat Sheet
// Simple solution
std::string result = name + std::to_string(age);
Rules
std::stringstores textintstores numbers- Convert numbers to strings before concatenation
- Include
#include <string>forstd::string - Include
#include <sstream>if using string streams
Common patterns
std::string a = "User" + std::to_string(7);
std::string b = std::string("User") + std::to_string(7);
Stream version
std::ostringstream oss;
oss << name << age;
std::string result = oss.str();
Printing is different from building a string
std::cout << name << age; // prints
std::string result = name + std::(age);
FAQ
Can I directly add an int to a std::string in C++?
No. You must first convert the integer into a string, usually with std::to_string.
What is the easiest way to concatenate a std::string and an integer?
Use:
std::string result = name + std::to_string(age);
Why does std::cout << name << age work if name + age does not?
std::cout uses stream insertion operators to print different types. String concatenation with + requires compatible string operands.
Should I use std::to_string or ostringstream?
Use std::to_string for simple cases. Use ostringstream when building more complex formatted strings.
Does "John" + 21 create "John21"?
No. With a string literal, with an integer performs pointer arithmetic, not string concatenation.
Mini Project
Description
Build a small C++ program that creates user profile labels by combining a user's name and age into one string. This demonstrates the exact skill of converting integers to strings before concatenation, which is useful in logs, filenames, IDs, and display labels.
Goal
Create a program that combines a std::string name and an int age into a single formatted string and prints it.
Requirements
- Declare a
std::stringvariable for a person's name. - Declare an
intvariable for the person's age. - Create a new string that combines both values.
- Print the final combined string.
- Use a modern C++ approach for number-to-string conversion.
Keep learning
Related questions
Advantages of Brace Initialization in C++
Learn why C++ brace initialization is often clearer and safer than other object initialization styles, with examples and common pitfalls.
Basic Rules and Idioms for Operator Overloading in C++
Learn the core rules, syntax, and common idioms for operator overloading in C++, including member vs non-member operators.
C++ Aggregates, Trivial Types, Trivially Copyable Types, and PODs Explained
Learn what aggregates, trivial types, trivially copyable types, and PODs mean in C++, how they differ, and why they matter.