Convert String to Integer in C++
Convert String to Integer in C++ (5 Programs).
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}
Output
String: 12345 Integer (method 1): 12345 Integer (method 2): 12345
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)
int num3 = atoi(str.c_str());
1#include <cstdlib>
Method 4: Using sscanf() (C-style)
int num4;
sscanf(str.c_str(), "%d", &num4);
1#include <cstdio>
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:
Output:
String: 12345
Integer (method 1): 12345
Integer (method 2): 12345
Both methods produce the same integer value.
1cout << "String: " << str << endl;2cout << "Integer (method 1): " << num1 << endl;3cout << "Integer (method 2): " << num2 << endl;
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) {
}
1// Handle error
atoi()
: Returns 0 for invalid input (no way to distinguish error from actual 0)
stringstream
: Sets failbit on error
if (ss.fail()) {
}
1// Handle error
Best Practice
: Use stoi() with try-catch for robust error handling.
When to Use Each Method
-
stoi()
: Best for most cases - simple, safe, modern C++
-
stringstream
: Best when converting multiple values or mixing types
-
atoi()
: Only for legacy code or when you need C compatibility
-
sscanf()
: When you need complex format parsing
-
Manual
: For learning or when you need custom conversion logic
return 0;
This ends the program successfully.