Convert Integer to String

Convert Integer to String in C++ (5 Programs)

BeginnerTopic: String Conversion Programs
Back

C++ Convert Integer to String Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main() {
    int num = 12345;
    
    // Method 1: Using to_string()
    string str1 = to_string(num);
    
    // Method 2: Using stringstream
    stringstream ss;
    ss << num;
    string str2 = ss.str();
    
    cout << "Integer: " << num << endl;
    cout << "String (method 1): " << str1 << endl;
    cout << "String (method 2): " << str2 << endl;
    
    return 0;
}
Output
Integer: 12345
String (method 1): 12345
String (method 2): 12345

Understanding Convert Integer to String

This program teaches you how to convert an integer into a string in C++. This conversion is essential when you need to display numbers as text, concatenate numbers with strings, write numbers to files, or format output. Understanding different conversion methods helps you choose the most appropriate approach for your specific needs.

---

1. What This Program Does

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"

---

2. 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.

---

3. 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.

---

4. 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"

---

5. 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"

---

6. Other Methods (Mentioned but not shown in code)

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

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
#include <cstdio>

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

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
#include <cstdlib>

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

---

7. 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)

---

8. Displaying Results

The program prints:

Output:

Integer: 12345
String (method 1): 12345
String (method 2): 12345

Both methods produce the same string value.

---

cout << "Integer: " << num << endl;
cout << "String (method 1): " << str1 << endl;
cout << "String (method 2): " << str2 << endl;

9. 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

---

10. 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

---

11. 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.

---

12. return 0;

This ends the program successfully.

---

Summary

Converting integers to strings is essential for output formatting and string operations.
to_string() is the recommended modern C++ method - simple, safe, and efficient.
stringstream is best when you need formatting or combining multiple values.
sprintf() and itoa() are C-style methods with various limitations.
Manual conversion helps understand how the process works internally.
Choose the method based on your specific needs: simplicity vs. flexibility.

This program is fundamental for beginners learning how to work with different data types, format output, and combine numbers with text in C++ programs.

Let us now understand every line and the components of the above program.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Practical Learning Notes for Convert Integer to String

This C++ program is part of the "String Conversion Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents