Articles

How to Convert a String to an Integer in C++

Learn how to convert string to integer in C++ using different methods like `std::stoi`, `std::istringstream`, `std::atoi`, `std::strtol`, `std::sscanf `, and `for` loop.

Introduction

In programming, we often need to work with numbers stored as strings. For example, let’s say we’re writing a program where a user enters their age or the price of an item as "123". We must first convert the string into an integer to do any calculations, comparisons, or logical operations on it.

C++ has various methods to implement it, each of which has advantages and disadvantages. This article explores some popular methods for converting a string to an integer, explaining their syntax, strengths, limitations, and the scenarios where each method is most effective.

We will start by learning the different methods to convert string to integer in C++.

Related Course

Learn C#: References

Unlock the power of references, an essential aspect of object-oriented programming in C#. Try it for free

1. Convert string to integer using std::stoi

The std::stoi function is short for “string to integer”. This function provides a modern and efficient way to convert a string into an integer, with clear syntax that is straightforward to understand and implement. As part of the C++ Standard Library, this function includes built-in error handling for invalid or out-of-range inputs, making it reliable for various scenarios.

Syntax:

int std::stoi(const std::string& str, size_t* idx = 0, int base = 10);
  • str: The string to be converted.

  • idx: (Optional) Pointer to store the index of the first invalid character.

  • base: (Optional) Base of the numeric system (default is 10 for decimal numbers).

Example:

Let’s look at an example to see how we can use std::stoi to convert a string into an integer while handling exceptions for invalid input.

#include <iostream>
#include <string>
int main() {
std::string str = "123"; // Input string
try {
// Convert string to integer
int num = std::stoi(str);
std::cout << "The integer is: " << num << std::endl;
} catch (const std::invalid_argument&) {
std::cout << "Invalid input: The string is not a valid number." << std::endl;
} catch (const std::out_of_range&) {
std::cout << "Number out of range." << std::endl;
}
return 0;
}

Output:

The integer is: 123 

Why Use It?

  • Pros: It’s easy to use and has error-handling capabilities.

  • Cons: Throws exceptions, which require additional handling in performance-critical scenarios.

2. Convert string to integer using std::istringstream

std::istringstream is part of the <sstream> library and is a handy tool for extracting data from strings. This method is particularly useful when dealing with strings containing mixed types of data, such as "123 apples".

Syntax:

std::istringstream iss(const std::string& str);
iss >> variable;
  • str: The input string.

  • variable: Variable in which to save the extracted integer.

Example:

The following example shows how std::istringstream extracts an integer from a string.

#include <iostream>
#include <sstream>
int main() {
std::string str = "456"; // Input string
std::istringstream iss(str);
int num;
// Extract integer from the string
iss >> num;
if (iss.fail()) {
std::cout << "Conversion failed: Invalid input." << std::endl;
} else {
std::cout << "The integer is: " << num << std::endl;
}
return 0;
}

Here,

  • std::istringstream iss(str): Initializes a string stream object using the input string str.

  • iss >> num: Extracts the integer value from the string and stores it in the variable num.

  • iss.fail(): Checks if the extraction failed (e.g., if the string contains non-numeric characters).

Output:

The integer is: 456 

Why Use It?

  • Pros: Very good for parsing strings with mixed content, such as “456 extra text”.

  • Cons: A bit verbose compared to std::stoi.

3. Convert string to integer using std::atoi

std::atoi stands for ASCII to integer. It is a legacy method from the C programming language for converting a C-style string (const char*) into an integer. However, this function lacks error handling, making it less reliable for modern applications.

Syntax:

int std::atoi(const char* str); 
  • str: C-style input string.

Example:

This example demonstrates how to use std::atoi to convert a string into an integer.

#include <iostream>
#include <cstdlib>
int main() {
const char* str = "789"; // Input C-style string
int num = std::atoi(str);
std::cout << "The integer is: " << num << std::endl;
return 0;
}

Output:

The integer is: 789 

Why Use It?

  • Pros: It’s simple and fast.

  • Cons: It does not handle errors. It returns 0 for invalid input, which may cause programs using this function to behave unexpectedly.

4. Convert string to integer using std::strtol

Thestd::strtol (string to long) method offers a more robust means of converting strings into integers than std::atoi. It provides better error handling and allows parsing of partially valid strings.

Syntax:

long int std::strtol(const char* str, char** endptr, int base);
  • str: The input string.

  • endptr: Pointer to the first invalid character.

  • base: Base for conversion (default is 10).

Example:

This example converts a string to an integer and identifies where parsing stopped.

#include <iostream>
#include <cstdlib>
int main() {
const char* str = "123abc"; // Input string
char* endptr;
int num = std::strtol(str, &endptr, 10);
// Check where parsing stopped
if (*endptr != '\0') {
std::cout << "Conversion stopped at: " << endptr << std::endl;
} else {
std::cout << "The integer is: " << num << std::endl;
}
return 0;
}

Output:

Conversion stopped at: abc 

Why Use It?

  • Pros: It handles partially valid strings like “123abc”.

  • Cons: Syntax slightly more complex thanstd::stoi.

5. Convert string to integer using a for loop

This manual approach converts a numeric string to an integer by processing one character at a time. It requires handling each character explicitly and building the integer step by step.

Syntax:

for (char c : str) {
num = num * 10 + (c - '0');
}
  • str: Input string containing numeric characters.

  • c: Each character in the string.

  • num: The resulting integer after processing the characters.

Example:

This example demonstrates how to manually convert the string "456" to an integer using a for loop.

#include <iostream>
#include <string>
int main() {
std::string str = "456"; // Input string
int num = 0;
// Convert string to integer manually
for (char c : str) {
// Check for invalid characters
if (c < '0' || c > '9') {
std::cout << "Invalid character in input." << std::endl;
return 1;
}
// Build the integer step by step
num = num * 10 + (c - '0');
}
std::cout << "The integer is: " << num << std::endl;
return 0;
}

Output:

The integer is: 456 

Why Use It?

  • Pros: It gives full control over the conversion process and is easily customizable for unique requirements (e.g., supporting specific character sets).

  • Cons: Error-prone compared to built-in functions like std::stoi. It requires more lines of code and is less efficient for large-scale operations.

6. Convert string to integer using std::sscanf

The std::sscanf() function is part of the <cstdio> library. It’s a C-style function that reads formatted data from strings.

Syntax:

int std::sscanf(const char* str, const char* format, ...); 
  • str: The input string.

  • format: Format specifier (e.g., %dfor integers).

  • ...: Variable(s) to store the parsed data. The variables must be passed as pointers (e.g., &num)

Example:

This example demonstrates how to use std::sscanf() to convert the string “789” into an integer.

#include <iostream>
#include <cstdio>
int main() {
const char* str = "789";
int num;
if (std::sscanf(str, "%d", &num) == 1) {
std::cout << "The integer is: " << num << std::endl;
} else {
std::cout << "Conversion failed: Invalid input." << std::endl;
}
return 0;
}

Output:

The integer is: 789 

Why Use It?

  • Pros: It is flexible for parsing formatted strings and can extract multiple values at a time.

  • Cons: It is a C-style function with less type safety.

Now that we’ve gone through the methods, let’s take a closer look at how they stack up in terms of strengths, weaknesses, and the situations they work best in.

Comparision between different methods to convert string to integer

Let’s compare different methods and see which method is fastest for string to integer conversion.

Method Pros Cons Best Use Case
std::stoi Simple, efficient, robust error handling. Throws exceptions that require handling. Converting straightforward numeric strings.
std::istringstream Good for parsing mixed content. Verbose compared to alternatives. Extracting integers from strings with mixed data.
std::atoi Fast and simple. No error handling, deprecated in modern C++. Legacy code.
std::strtol Handles partially valid strings. Slightly complex syntax. Converting strings with trailing or mixed characters.
For loop Full control over conversion. Manual and error-prone. Teaching and learning conversion logic.
std::sscanf Flexible and good for formatted string. Verbose and less type-safe. Parsing strings with a defined pattern.

Conclusion

Converting strings to integers in C++ is essential for working with data. Modern methods like std::stoi and std::istringstream are preferred for their robustness and error handling, while legacy methods like std::atoi and std::strtol are still relevant in specific use cases.

Each method we’ve explored has its unique advantages. The versatility of C++ ensures that there’s a solution for every situation, making it easier to handle data with confidence and precision.

For more C++ programming tips, explore Codecademy’s C++ course.

Author

Codecademy Team

'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'

Meet the full team