Convert String to Integer
Convert String to Integer in C++ (5 Programs)
C++ Convert String to Integer Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string str = "12345";
// Method 1: Using stoi()
int num1 = stoi(str);
// Method 2: Using stringstream
stringstream ss(str);
int num2;
ss >> num2;
cout << "String: " << str << endl;
cout << "Integer (method 1): " << num1 << endl;
cout << "Integer (method 2): " << num2 << endl;
return 0;
}String: 12345 Integer (method 1): 12345 Integer (method 2): 12345
Understanding Convert String to Integer
This program teaches you how to convert a string containing numeric characters into an integer in C++. This is one of the most common operations in programming, especially when reading user input, parsing files, or processing data from external sources. Understanding different conversion methods helps you choose the best approach for your specific needs.
---
1. What This Program Does
The program converts a string like "12345" into an integer value 12345. This conversion is necessary because:
Example:
---
2. Header Files Used
---
3. Declaring Variables
The program declares:
string str = "12345";
---
4. 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:
---
5. 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
---
6. Other Methods (Mentioned but not shown in code)
Method 3: Using atoi() (C-style)
int num3 = atoi(str.c_str());
#include <cstdlib>Method 4: Using sscanf() (C-style)
int num4;
sscanf(str.c_str(), "%d", &num4);
#include <cstdio>Method 5: Manual Conversion
int num5 = 0;
if (c >= '0' && c <= '9') {
num5 = num5 * 10 + (c - '0');
}
}
---
7. How Manual Conversion Works (Step-by-Step)
Understanding manual conversion helps you understand the concept:
For string "12345":
---
8. Displaying Results
The program prints:
Output:
Both methods produce the same integer value.
---
cout << "String: " << str << endl;
cout << "Integer (method 1): " << num1 << endl;
cout << "Integer (method 2): " << num2 << endl;9. Error Handling
Different methods handle errors differently:
stoi()
try {
int num = stoi("abc");
}
// Handle erroratoi()
: Returns 0 for invalid input (no way to distinguish error from actual 0)
stringstream
: Sets failbit on error
if (ss.fail()) {
}
// Handle errorBest Practice
: Use stoi() with try-catch for robust error handling.
---
10. 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
---
11. return 0;
This ends the program successfully.
---
Summary
This program is crucial for beginners learning how to work with different data types and process user input 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 String to Integer
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.