Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Convert Integer to String in C++

Convert an int to a std::string in C++ with to_string or a stringstream. See when each is handy, how to pad with zeros, and why char(num) is not the same thing.

BeginnerString Conversion ProgramsExample 4 of 11
convert-integer-to-string.cpp
1#include <iostream>
2#include <string>
3#include <sstream>
4using namespace std;
5
6int main() {
7 int num = 12345;
8
9 // Method 1: Using to_string()
10 string str1 = to_string(num);
11
12 // Method 2: Using stringstream
13 stringstream ss;
14 ss << num;
15 string str2 = ss.str();
16
17 cout << "Integer: " << num << endl;
18 cout << "String (method 1): " << str1 << endl;
19 cout << "String (method 2): " << str2 << endl;
20
21 return 0;
22}

Sample Output

String (method 1): 12345

From to_string.

In this one

  • How to_string turns a number into text
  • How stringstream << builds text from numbers
  • How ss.str() reads the built string
  • How to add zero padding with setw and setfill

How it works

  1. 1

    num holds 12345.

  2. 2

    to_string(num) gives "12345".

  3. 3

    ss << num writes the digits into a stringstream.

  4. 4

    ss.str() copies them out as a string.

  5. 5

    Print all three.

Edge cases

Negative number

Set num = -42.

to_string gives "-42", with the minus sign included in the text.

Casting instead of converting

Write string s(1, char(num));

That makes one character with code num, not the digits. For 65 you get "A", not "65".

What's going on

The program converts an integer (like 12345) into a string (like "12345"). This conversion is necessary because:

You need to combine numbers with text in output
File operations often require string format
String manipulation functions work with strings, not integers
Display formatting sometimes requires string conversion

Example:

Input integer: 12345
Output string: "12345"

Header Files Used

1.#include <iostream>
Provides cout and cin for input/output operations.
2.#include <string>
Essential for using the string data type.
Required for to_string() function and string operations.
3.#include <sstream>
Provides stringstream class for string-based input/output operations.
Allows treating strings as streams for formatting.

Declaring Variables

The program declares:

int num = 12345;

int is the data type for storing whole numbers.
num stores the integer value 12345 that we want to convert to a string.

Method 1: Using to_string() (Integer to String)

string str1 = to_string(num);

This is the most modern and recommended method in C++:

to_string() is a built-in function (C++11 and later)
It's part of the <string> header
It automatically handles the conversion
Works with all numeric types (int, float, double, etc.)

How it works:

to_string(12345) converts the integer directly to string "12345"
Simple, clean, and efficient
No additional setup required

Advantages:

Simplest syntax
Type-safe
Handles all numeric types
Most readable code

Example:

int n = 12345;

string s = to_string(n); // s = "12345"

Method 2: Using stringstream

stringstream ss;

ss << num;

string str2 = ss.str();

This method uses stringstream to convert the integer:

stringstream ss creates an empty stream object
ss << num inserts the integer into the stream (like cout <<)
ss.str() extracts the string representation from the stream

How it works:

1.Create an empty stringstream object
2.Insert the integer using the << operator
3.Extract the string using .str() method

Advantages:

Very flexible - can format numbers (precision, width, etc.)
Can combine multiple values into one string
Similar syntax to cout, making it familiar

Example with formatting:

stringstream ss;

ss << fixed << setprecision(2) << 123.45;

string s = ss.str(); // s = "123.45"

Example with multiple values:

stringstream ss;

ss << "Number: " << 12345 << " is an integer";

string s = ss.str(); // s = "Number: 12345 is an integer"

Other Methods (Mentioned but not shown in code)

Method 3: Using sprintf() (C-style)

#include <cstdio>

char buffer[20];

sprintf(buffer, "%d", num);

string str3 = buffer;

sprintf() formats and stores output in a character array
Requires a buffer (character array) to store the result
"%d" is the format specifier for integers
Less safe - buffer overflow risk if number is too large

Method 4: Using itoa() (Non-standard, C-style)

#include <cstdlib>

char buffer[20];

itoa(num, buffer, 10); // 10 = base 10 (decimal)

string str4 = buffer;

itoa() converts integer to ASCII string
Not standard C++ (may not be available on all compilers)
Requires specifying the number base (10 for decimal)
Less portable

Method 5: Manual Conversion

string str5 = "";

int temp = num;

if (temp == 0) str5 = "0";

else {

bool negative = temp < 0;

if (negative) temp = -temp;

while (temp > 0) {

str5 = char('0' + temp % 10) + str5;

temp /= 10;

}

if (negative) str5 = "-" + str5;

}

Manually extracts each digit
Most control but most code
Useful for learning how conversion works internally
Handles negative numbers and zero

How Manual Conversion Works (Step-by-Step)

Understanding manual conversion helps you understand the concept:

For integer 12345:

1.Extract last digit: 12345 % 10 = 5, add '5' to string
2.Remove last digit: 12345 / 10 = 1234
3.Extract last digit: 1234 % 10 = 4, add '4' to front: "45"
4.Remove last digit: 1234 / 10 = 123
5.Extract last digit: 123 % 10 = 3, add '3' to front: "345"
6.Continue until number becomes 0
7.Final string: "12345"

The process:

Use modulo (%) to get the last digit
Use division (/) to remove the last digit
Convert digit to character: '0' + digit
Build string from right to left (or reverse at end)

Displaying Results

The program prints:

cout << "Integer: " << num << endl;

cout << "String (method 1): " << str1 << endl;

cout << "String (method 2): " << str2 << endl;

Output:

Integer: 12345

String (method 1): 12345

String (method 2): 12345

Both methods produce the same string value.

When to Use Each Method

to_string(): Best for most cases - simple, safe, modern C++
stringstream: Best when you need formatting or combining multiple values
sprintf(): Only for legacy code or when you need C compatibility
itoa(): Avoid - not standard, not portable
Manual: For learning or when you need custom conversion logic

Formatting Considerations

With to_string(): Basic conversion, no formatting options

string s = to_string(123.456); // "123.456000" (default precision)

With stringstream: Full formatting control

stringstream ss;

ss << fixed << setprecision(2) << 123.456;

string s = ss.str(); // "123.46"

For integers: to_string() is usually sufficient

For floats/doubles: stringstream gives better control over decimal places

Performance Considerations

to_string(): Fastest and most efficient for simple conversions
stringstream: Slightly slower but more flexible
sprintf(): Fast but less safe (buffer management)
Manual: Slowest but most educational

For most applications, the performance difference is negligible. Choose based on code clarity and requirements.

return 0;

This ends the program successfully.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is to_string(5).length()?

Pick an answer to check it.

Question 2

What does "Age: " + to_string(20) give?

Pick an answer to check it.

Questions people ask

Which is faster?

to_string is shorter and usually faster. stringstream is useful when you need formatting like padding or mixing several values.

How do I get "007" from 7?

ss << setw(3) << setfill('0') << 7; with <iomanip>.

Can I add a number to a string with +?

Not directly. Use str + to_string(num).