Convert String to Integer in C++

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

BeginnerString Conversion ProgramsExample 3 of 11
convert-string-to-integer.cpp
1#include <iostream>
2#include <string>
3#include <sstream>
4using namespace std;
5
6int main() {
7 string str = "12345";
8
9 // Method 1: Using stoi()
10 int num1 = stoi(str);
11
12 // Method 2: Using stringstream
13 stringstream ss(str);
14 int num2;
15 ss >> num2;
16
17 cout << "String: " << str << endl;
18 cout << "Integer (method 1): " << num1 << endl;
19 cout << "Integer (method 2): " << num2 << endl;
20
21 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:

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

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.

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.

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

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

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

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)

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.