Question

How to Convert int to String in C++

cppstringtype-conversioninteger

Question

How can I convert an int to its equivalent std::string in C++?

I am aware of these two approaches and want to know whether there is another recommended way.

int a = 10;
char* intStr = itoa(a);
std::string str = std::string(intStr);
int a = 10;
std::stringstream ss;
ss << a;
std::string str = ss.str();

Short Answer

By the end of this page, you will understand how to convert an int to a std::string in C++, which methods are modern and recommended, and when older techniques like stringstream or C-style conversion functions are still seen in code.

Concept

In C++, converting an int to a std::string means turning a numeric value like 42 into text like "42".

This matters because numbers and strings are used for different purposes:

  • Numbers are for calculation.
  • Strings are for display, storage, logging, filenames, JSON, and user messages.

For example, if you want to build a message such as:

"User score: " + score

you cannot directly add an int to a std::string. You must first convert the number into text.

Modern C++ approach

The most common and recommended modern solution is:

std::to_string(a)

This is simple, readable, and part of the C++ standard library.

Why not always use older methods?

itoa

  • itoa is not part of the C++ standard.
  • It may work on some compilers, but it is not portable.
  • Code using it may fail on another platform or compiler.

stringstream

  • stringstream is standard and portable.
  • It is useful when you are formatting multiple values.
  • But for a simple int to string conversion, it is more verbose than necessary.

So the core idea is:

  • Use std::to_string for simple conversions.
  • Use std::stringstream when you need more formatting control or are working in older codebases.

Mental Model

Think of an int as a quantity in your head, like the number 25, and a std::string as the written label "25" on paper.

The value is the same idea, but the representation is different:

  • 25 as an int can be added, multiplied, or compared numerically.
  • "25" as a std::string is just text characters: '2' and '5'.

Converting int to string is like writing a number down so it can be displayed, stored in text, or combined with other text.

Take Quiz

Syntax and Examples

Recommended syntax

#include <string>

int a = 10;
std::string str = std::to_string(a);

This creates the string "10" from the integer 10.

Full example

#include <iostream>
#include <string>

int main() {
    int age = 25;
    std::string text = std::to_string(age);

    std::cout << text << '\n';
    return 0;
}

Output:

25

Using stringstream

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

int main() {
    int value = 42;
    std::stringstream ss;
    ss << value;

    std::string text = ss.str();
    std::cout << text << '\n';
    return 0;
}

This also works, but it is longer than std::to_string.

Converting while building a message

#include <iostream>
#include <string>

int main() {
    int score = 99;
    std::string message = "Score: " + std::to_string(score);

    std::cout << message << '\n';
    return 0;
}

Output:

Score: 99

Older non-recommended approach: itoa

// Not portable C++

itoa is not standard C++, so it should generally be avoided in portable programs.

Step by Step Execution

Consider this example:

#include <iostream>
#include <string>

int main() {
    int a = 10;
    std::string str = std::to_string(a);
    std::cout << str << '\n';
}

Here is what happens step by step:

  1. int a = 10;

    • A variable named a is created.
    • It stores the numeric value 10.
  2. std::string str = std::to_string(a);

    • std::to_string(a) reads the integer value 10.
    • It converts that number into the text "10".
    • The result is stored in str.
  3. std::cout << str << '\n';

    • The program prints the string to the console.
    • The output is 10.

Important detail:

  • Before conversion, a is a number.
  • After conversion, str is text.
  • They may look similar when printed, but they are different types and used differently.

Real World Use Cases

Converting integers to strings is very common in real programs.

Displaying values to users

std::string label = "Lives left: " + std::to_string(lives);

Used in:

  • games
  • desktop apps
  • command-line tools
  • dashboards

Logging and debugging

std::string logMessage = "User ID=" + std::to_string(userId);

Useful for:

  • error logs
  • trace messages
  • diagnostics

Building filenames

std::string filename = "report_" + std::to_string(reportNumber) + ".txt";

Useful for:

  • exported files
  • backups
  • generated reports

Creating API or JSON values as text

Sometimes numeric values need to be inserted into text payloads.

std::string json = "{\"count\": \"" + std::to_string(count) + "\"}";

Forming SQL or command strings carefully

std::string queryInfo = "Processing batch " + std::to_string(batchId);

Even when full query builders are preferred, integer-to-string conversion still appears often in supporting text.

Take Quiz

Real Codebase Usage

In real codebases, developers usually pick the conversion method based on readability, portability, and formatting needs.

Common pattern: direct conversion

std::string idText = std::to_string(id);

This is the most common approach for a plain conversion.

Common pattern: message construction

if (count < 0) {
    return "Invalid count: " + std::to_string(count);
}

This often appears in:

  • validation messages
  • exceptions
  • logging
  • status output

Common pattern: early return with conversion

if (userId == 0) {
    return "Anonymous user";
}

return "User #" + std::to_string(userId);

This is a clean example of a guard clause plus conversion.

Using stringstream for formatting-heavy code

std::stringstream ss;
ss << "Order " << orderId << " has total " << total;
std::string text = ss.str();

Developers may choose this when:

  • combining many values
  • mixing text and numbers
  • using formatting manipulators

Validation and error reporting

if (port < 1 || port > 65535) {
    throw std::runtime_error("Invalid port: " + std::to_string(port));
}

This is practical, readable, and common in production code.

Common Mistakes

1. Using itoa as if it were standard C++

Broken assumption:

int a = 10;
char* s = itoa(a);

Problem:

  • itoa is not part of the C++ standard library.
  • It may not compile everywhere.

Prefer:

std::string s = std::to_string(a);

2. Forgetting the std:: namespace

Broken code:

string s = to_string(10);

Unless you introduced those names properly, this will fail.

Correct:

std::string s = std::to_string(10);

3. Missing the required header

Broken code:

std::string s = std::to_string(10);

Without:

#include <string>

Always include the right headers.

4. Confusing numeric addition with string concatenation

Broken thinking:

int a = 2;
int b = 3;
std::string s = std::to_string(a + b); // gives "5", not "23"

If you want to join digits as text, convert separately:

std::string s = std::to_string(a) + std::to_string(b); // "23"

5. Trying to add a string literal and an int directly

Broken code:

int score = 50;
std::string msg = "Score: " + score;

Problem:

  • score is not text.

Correct:

std::string msg = std::string("Score: ") + std::to_string(score);

Or simply:

std::string msg = "Score: " + std::to_string(score);

6. Overusing stringstream for simple conversions

This is valid:

std::stringstream ss;
ss << value;
std::string text = ss.str();

But if all you need is a basic integer-to-string conversion, std::to_string is clearer and shorter.

Comparisons

MethodStandard C++Easy to readBest use caseNotes
std::to_string(int)YesYesSimple numeric-to-string conversionBest default choice
std::stringstreamYesModerateComplex formatting or mixing many valuesMore verbose
itoaNoModerateLegacy or compiler-specific codeNot portable

std::to_string vs stringstream

  • Use std::to_string when you only need to convert a number.
  • Use stringstream when you are building more complex formatted text.

Example:

std::string a = std::to_string(123);

vs.

std::stringstream ss;
ss << "Value: " << 123;
std::string b = ss.str();

std::string vs C-style strings

TypeDescription
std::stringModern C++ string class
char*Pointer to C-style character array

In modern C++, prefer std::string because it is safer and easier to use.

Take Quiz

Cheat Sheet

Quick reference

Convert int to std::string

std::string s = std::to_string(123);

Required header

#include <string>

Alternative using stringstream

#include <sstream>

std::stringstream ss;
ss << 123;
std::string s = ss.str();

Recommended choice

  • Use std::to_string() for simple conversions.
  • Use stringstream for more formatting control.
  • Avoid itoa in portable C++ code.

Common patterns

std::string message = "Count: " + std::to_string(count);
throw std::runtime_error("Invalid value: " + std::to_string(value));

Edge cases

  • std::to_string(0) gives "0"
  • Negative numbers work: std::to_string(-7) gives "-7"
  • The result is text, not a number

FAQ

Is std::to_string the best way to convert int to string in C++?

Yes, for most simple cases. It is standard, readable, and concise.

Is itoa standard in C++?

No. itoa is not part of the C++ standard library, so it is not portable.

When should I use stringstream instead of std::to_string?

Use stringstream when you need more complex formatting or want to combine many values into one string.

Do I need to include a header for std::to_string?

Yes. Include:

#include <string>

Can I convert negative integers to strings?

Yes.

std::string s = std::to_string(-42);

This produces "-42".

Can I concatenate an int directly with a string in C++?

No. Convert the int first:

std::string msg = "Value: " + std::to_string(value);

Does converting an int to a string change the original number?

No. It creates a new string representation. The original integer stays unchanged.

Take Quiz

Mini Project

Description

Build a small console program that prints user-friendly status messages using integer-to-string conversion. This demonstrates how numbers are turned into text for display, logging, and message building in everyday C++ code.

Goal

Create a program that stores a few integer values and prints readable messages by converting them to std::string.

Requirements

  • Create at least two integer variables such as a score and a level.
  • Convert each integer to a std::string using a standard C++ approach.
  • Build and print at least two complete messages that include both text and numbers.
  • Avoid using itoa.
  • Keep the program valid modern C++.
Take Quiz

Keep learning

Related questions

View more