Question

How to Concatenate a std::string and an int in C++

cppintegerconcatenationstdstring

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 text
  • 21 as 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.

Take Quiz

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

  • name is already a std::string
  • std::to_string(age) converts 21 into the string "21"
  • now both parts are strings, so + can concatenate them

Another example

#include <string>
#include <iostream>

int main() {
    std::string product = "item_";
    int id = 42;

    std::string code = product + std::to_string(id);
    std::cout << code << '\n';
}

Output:

item_42

Using string streams

Another common approach is std::ostringstream:

#include <string>
#include <sstream>
#include <iostream>

int main() {
    std::string name = "John";
    int age = 21;

    std::ostringstream oss;
    oss << name << age;

    std::string result = oss.str();
    std::cout << result << '\n';
}

This is especially useful when combining many different values or formatting output.

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:

  1. std::string name = "John";

    • Creates a string variable containing the text "John".
  2. int age = 21;

    • Creates an integer variable containing the number 21.
  3. std::to_string(age)

    • Converts the integer 21 into the string "21".
  4. name + std::to_string(age)

    • Concatenates "John" and "21".
    • The result becomes "John21".
  5. std::string result = ...

    • Stores the final combined string in result.
  6. std::cout << result << '\n';

    • Prints John21.

Small trace

ExpressionValue
name"John"
age21
std::to_string(age)"21"
name + std::to_string(age)"John21"

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.

Take Quiz

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:

  • cache keys
  • database record labels
  • log prefixes
  • generated IDs
  • file paths

In production code, the main goal is clarity. If std::to_string makes the expression easy to read, it is usually the best option.

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:

  • name is text
  • age is a number
  • C++ does not automatically convert the int to std::string here

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:

std::cout << name << age;

But it does not create a combined std::string variable.

If you need a string value, do this instead:

std::string result = name + std::to_string(age);

Mistake 4: Assuming "text" + number always means concatenation

This can be dangerous with C-style string literals:

auto x = "John" + 2;

This does not produce "John2". It performs pointer arithmetic on the string literal.

For example, "John" + 2 points to the substring starting at index 2, which is:

"hn"

Avoid this by using std::string explicitly:

std::string result = std::string("John") + std::to_string(2);

Mistake 5: Using old conversion functions without need

Older code may use sprintf, itoa, or manual buffers. These are usually less safe or less clear than std::to_string for simple use cases.

Prefer modern C++ when possible.

Comparisons

Here is how common approaches compare.

ApproachExampleBest forNotes
std::to_stringname + std::to_string(age)Simple concatenationClear and modern
std::ostringstreamoss << name << ageComplex string buildingFlexible for many values
std::cout <<std::cout << name << agePrinting onlyDoes not create a std::string
C-style formattingsprintf(...)Legacy codeLess safe and less idiomatic in modern C++

std::to_string vs std::ostringstream

Featurestd::to_stringstd::ostringstream
Easy to read for simple casesYesUsually more verbose
Good for many mixed valuesSometimesYes
Good for custom formattingLimitedBetter
Modern beginner-friendly choiceYesYes

Recommendation

  • Use std::to_string for simple number-to-string conversion.
  • Use std::ostringstream when building larger formatted messages.
Take Quiz

Cheat Sheet

// Simple solution
std::string result = name + std::to_string(age);

Rules

  • std::string stores text
  • int stores numbers
  • Convert numbers to strings before concatenation
  • Include #include <string> for std::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::to_string(age); // stores string

Avoid

std::string result = name + age; // wrong
auto x = "John" + 2;            // pointer arithmetic, not concatenation

Result example

std::string name = "John";
int age = 21;
std::string result = name + std::to_string(age); // "John21"

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.

Is std::to_string available in all C++ versions?

It is available from C++11 onward.

How do I concatenate multiple values into one string?

You can chain conversions:

std::string result = name + std::to_string(age) + "_active";

Or use a stream for larger expressions.

Take Quiz

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::string variable for a person's name.
  • Declare an int variable 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.
Take Quiz

Keep learning

Related questions

View more