C++ How to Convert int to string Easily
In C++, you can convert an int to a string using
std::to_string(yourInt), which returns the string form of the integer.Examples
Input123
Output"123"
Input0
Output"0"
Input-456
Output"-456"
How to Think About It
To convert an integer to a string, think of turning the number into text that you can print or use as words. The standard way is to use a built-in function that takes the number and gives back its string form.
Algorithm
1
Take the integer value you want to convert.2
Use the built-in function to convert the integer to a string.3
Store or use the resulting string as needed.Code
cpp
#include <iostream> #include <string> int main() { int number = 123; std::string text = std::to_string(number); std::cout << text << std::endl; return 0; }
Output
123
Dry Run
Let's trace converting the integer 123 to a string.
1
Start with integer
number = 123
2
Convert to string
text = std::to_string(123) -> "123"
3
Print string
Output: 123
| Step | Variable | Value |
|---|---|---|
| 1 | number | 123 |
| 2 | text | "123" |
| 3 | output | 123 |
Why This Works
Step 1: Using std::to_string
The function std::to_string takes an integer and returns its string representation.
Step 2: Storing the result
The returned string can be stored in a std::string variable for further use.
Step 3: Printing the string
You can print the string using std::cout to see the number as text.
Alternative Approaches
Using stringstream
cpp
#include <iostream> #include <sstream> #include <string> int main() { int number = 123; std::stringstream ss; ss << number; std::string text = ss.str(); std::cout << text << std::endl; return 0; }
This method works in older C++ versions but is more verbose than std::to_string.
Using sprintf (C-style)
cpp
#include <iostream> #include <cstdio> int main() { int number = 123; char buffer[20]; sprintf(buffer, "%d", number); std::string text(buffer); std::cout << text << std::endl; return 0; }
This is a C-style approach and less safe; prefer std::to_string in modern C++.
Complexity: O(n) time, O(n) space
Time Complexity
Converting an integer to string takes time proportional to the number of digits, so O(n) where n is digit count.
Space Complexity
The string requires space proportional to the number of digits, so O(n) extra space.
Which Approach is Fastest?
std::to_string is generally fastest and simplest; stringstream is slower due to stream overhead; sprintf is fast but less safe.
| Approach | Time | Space | Best For |
|---|---|---|---|
| std::to_string | O(n) | O(n) | Modern, simple code |
| stringstream | O(n) | O(n) | Older C++ versions, flexible formatting |
| sprintf | O(n) | O(n) | Legacy C-style code, but less safe |
Use
std::to_string for a simple and safe int to string conversion in C++.Trying to assign an int directly to a string without conversion causes errors.