Convert String to Integer

Convert String to Integer in C++ (5 Programs)

BeginnerTopic: String Conversion Programs
Back

C++ Convert String to Integer Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#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;
}
Output
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:

User input from cin is often read as strings
File data is typically read as strings
Network data comes as strings
You need integers for mathematical operations

Example:

Input string: "12345"
Output integer: 12345

---

2. Header Files Used

1.#include <iostream>
Provides cout and cin for input/output operations.
2.#include <string>
Essential for using the string data type.
Required for stoi() function and string operations.
3.#include <sstream>
Provides stringstream class for string-based input/output operations.
Allows treating strings as streams, similar to cin/cout.

---

3. Declaring Variables

The program declares:

string str = "12345";

string is the data type for storing text.
str stores the string "12345", which contains numeric characters.
Note: "12345" is text, not a number, until converted.

---

4. Method 1: Using stoi() (String to Integer)

int num1 = stoi(str);

This is the most modern and recommended method in C++:

stoi() stands for "string to integer"
It's part of the <string> header (C++11 and later)
It automatically handles the conversion
It throws exceptions for invalid input

How it works:

stoi("12345") reads the string and converts it to integer 12345
If the string contains non-numeric characters, it converts up to the first invalid character
Example: stoi("123abc") returns 123

Advantages:

Simple and clean syntax
Built-in error handling (throws exceptions)
Handles leading/trailing whitespace automatically
Most efficient for simple conversions

---

5. Method 2: Using stringstream

stringstream ss(str);

int num2;

ss >> num2;

This method uses stringstream, which treats a string like an input stream:

stringstream ss(str) creates a stream from the string
ss >> num2 extracts the integer from the stream, just like cin >> num

How it works:

1.Create a stringstream object from the string
2.Use the extraction operator (>>) to read the integer
3.The stream automatically converts the string to integer

Advantages:

Very flexible - can convert multiple values
Similar syntax to cin, making it familiar
Can handle multiple types in one stream

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());

atoi() is a C function that converts C-style strings (char arrays)
Requires converting C++ string to C-string using .c_str()
Returns 0 for invalid input (no error checking)
Less safe than stoi()
#include <cstdlib>

Method 4: Using sscanf() (C-style)

int num4;

sscanf(str.c_str(), "%d", &num4);

sscanf() reads formatted input from a string
Similar to scanf() but reads from a string
More control over format, but more complex
#include <cstdio>

Method 5: Manual Conversion

int num5 = 0;

for (char c : str) {

if (c >= '0' && c <= '9') {

num5 = num5 * 10 + (c - '0');

}

}

Manually processes each character
Most control but most code
Useful for learning how conversion works internally

---

7. How Manual Conversion Works (Step-by-Step)

Understanding manual conversion helps you understand the concept:

For string "12345":

1.Start with num = 0
2.Read '1': num = 0 * 10 + 1 = 1
3.Read '2': num = 1 * 10 + 2 = 12
4.Read '3': num = 12 * 10 + 3 = 123
5.Read '4': num = 123 * 10 + 4 = 1234
6.Read '5': num = 1234 * 10 + 5 = 12345
The formula: num = num * 10 + (character - '0')
Multiply by 10 shifts digits left
(c - '0') converts character to digit (e.g., '5' - '0' = 5)

---

8. Displaying Results

The program prints:

Output:

String: 12345
Integer (method 1): 12345
Integer (method 2): 12345

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()

: 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.

---

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

Converting strings to integers is essential for processing user input and data.
stoi() is the recommended modern C++ method - simple and safe.
stringstream is flexible and great for multiple conversions.
atoi() and sscanf() are C-style methods with less safety.
Manual conversion helps understand how the process works internally.
Always handle errors appropriately, especially with user input.

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.

Table of Contents