Convert String to Integer in C++
Convert a numeric string like "12345" into an int in C++ with stoi or stringstream. Learn which one throws on bad input and how to check a failed stream read.
1#include <iostream>2#include <string>3#include <sstream>4using namespace std;56int main() {7 string str = "12345";89 // Method 1: Using stoi()10 int num1 = stoi(str);1112 // Method 2: Using stringstream13 stringstream ss(str);14 int num2;15 ss >> num2;1617 cout << "String: " << str << endl;18 cout << "Integer (method 1): " << num1 << endl;19 cout << "Integer (method 2): " << num2 << endl;2021 return 0;22}
Sample Output
Integer (method 1): 12345
From stoi.
Integer (method 2): 12345
From stringstream.
In this one
- How stoi converts text and throws on bad input
- How stringstream >> extracts a number
- How to detect a failed stringstream read
- Why atoi is risky (it returns 0 on failure)
When to use this
Use this when numbers arrive as text, such as from a file, a command-line argument, or a line read with getline.
How it works
- 1
str holds "12345".
- 2
stoi(str) returns 12345.
- 3
A stringstream is built from str and >> extracts 12345 into num2.
- 4
Print the string and both integers.
Edge cases
Non-numeric text
Set str = "abc".
stoi throws std::invalid_argument, and without a try/catch the program ends. The stringstream read fails silently and, since C++11, stores 0, so check if (ss >> num2).
Trailing junk
Set str = "42abc".
stoi returns 42 and ignores the rest. Pass a size_t* as the second argument to learn where parsing stopped.
What's going on
The program converts a string like "12345" into an integer value 12345. This conversion is necessary because:
Example:
Header Files Used
Declaring Variables
The program declares:
string str = "12345";
Method 1: Using stoi() (String to Integer)
int num1 = stoi(str);
This is the most modern and recommended method in C++:
How it works:
Advantages:
Method 2: Using stringstream
stringstream ss(str);
int num2;
ss >> num2;
This method uses stringstream, which treats a string like an input stream:
How it works:
Advantages:
Example for multiple values:
stringstream ss("123 456 789");
int a, b, c;
ss >> a >> b >> c; // a=123, b=456, c=789
Other Methods (Mentioned but not shown in code)
Method 3: Using atoi() (C-style)
#include <cstdlib>
int num3 = atoi(str.c_str());
Method 4: Using sscanf() (C-style)
#include <cstdio>
int num4;
sscanf(str.c_str(), "%d", &num4);
Method 5: Manual Conversion
int num5 = 0;
for (char c : str) {
if (c >= '0' && c <= '9') {
num5 = num5 * 10 + (c - '0');
}
}
How Manual Conversion Works (Step-by-Step)
Understanding manual conversion helps you understand the concept:
For string "12345":
The formula: num = num * 10 + (character - '0')
Displaying Results
The program prints:
cout << "String: " << str << endl;
cout << "Integer (method 1): " << num1 << endl;
cout << "Integer (method 2): " << num2 << endl;
Output:
String: 12345
Integer (method 1): 12345
Integer (method 2): 12345
Both methods produce the same integer value.
Error Handling
Different methods handle errors differently:
stoi(): Throws std::invalid_argument or std::out_of_range exceptions
try {
int num = stoi("abc");
} catch (const std::exception& e) {
// Handle error
}
atoi(): Returns 0 for invalid input (no way to distinguish error from actual 0)
stringstream: Sets failbit on error
if (ss.fail()) {
// Handle error
}
Best Practice: Use stoi() with try-catch for robust error handling.
When to Use Each Method
return 0;
This ends the program successfully.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does stoi("abc") do?
Pick an answer to check it.
Question 2
How do you check a stringstream read?
Pick an answer to check it.
Questions people ask
What does stoi do with a number too big for int?
It throws std::out_of_range.
Is atoi a good alternative?
atoi returns 0 for bad input, so you cannot tell "0" from "abc". stoi reports errors.
Can stoi read other bases?
Yes: stoi("ff", nullptr, 16) gives 255.