C++ How to Convert String to Int Easily
In C++, you can convert a string to an int using the
stoi function like this: int num = std::stoi(str); where str is your string.Examples
Input"123"
Output123
Input"0"
Output0
Input"-456"
Output-456
How to Think About It
To convert a string to an int, think of reading the number characters one by one and turning them into a real number. The
stoi function does this by checking the string and extracting the integer value it represents.Algorithm
1
Take the input string that contains digits.2
Use a built-in function to parse the string and convert it to an integer.3
Store or return the integer value.Code
cpp
#include <iostream> #include <string> int main() { std::string str = "123"; int num = std::stoi(str); std::cout << num << std::endl; return 0; }
Output
123
Dry Run
Let's trace converting the string "123" to an int using stoi.
1
Input string
str = "123"
2
Call stoi
num = std::stoi("123")
3
Result
num = 123 (integer)
| Step | String | Integer Value |
|---|---|---|
| 1 | "123" | N/A |
| 2 | "123" | 123 |
| 3 | N/A | 123 |
Why This Works
Step 1: Using std::stoi
The stoi function reads the string and converts the numeric characters into an integer value.
Step 2: Handling signs
If the string starts with a minus sign, stoi correctly converts it to a negative integer.
Step 3: Error handling
stoi throws an exception if the string does not represent a valid integer.
Alternative Approaches
Using stringstream
cpp
#include <iostream> #include <sstream> #include <string> int main() { std::string str = "123"; std::stringstream ss(str); int num; ss >> num; std::cout << num << std::endl; return 0; }
This method is more flexible but slightly slower than stoi.
Using atoi (legacy)
cpp
#include <iostream> #include <cstdlib> int main() { const char* cstr = "123"; int num = std::atoi(cstr); std::cout << num << std::endl; return 0; }
This is an older C-style method that does not throw exceptions but requires a C-string.
Complexity: O(n) time, O(1) space
Time Complexity
The conversion scans each character once, so it takes linear time relative to the string length.
Space Complexity
No extra space is needed besides a few variables, so it uses constant space.
Which Approach is Fastest?
stoi is generally faster and safer than stringstream or atoi because it is optimized and throws exceptions on errors.
| Approach | Time | Space | Best For |
|---|---|---|---|
| std::stoi | O(n) | O(1) | Simple, safe, modern C++ |
| stringstream | O(n) | O(1) | Flexible parsing, multiple types |
| atoi | O(n) | O(1) | Legacy code, C-style strings |
Use
std::stoi for simple and safe string to int conversion in modern C++.Trying to convert strings with non-digit characters without handling exceptions causes runtime errors.