Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

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.

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}

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

    str holds "12345".

  2. 2

    stoi(str) returns 12345.

  3. 3

    A stringstream is built from str and >> extracts 12345 into num2.

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

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)

#include <cstdlib>

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

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

#include <cstdio>

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

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:

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

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.

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.