How can I convert a std::string to int?
Categories:
Converting std::string to int in C++: A Comprehensive Guide

Learn various robust methods to convert std::string
to int
in C++, including error handling, performance considerations, and best practices.
Converting a std::string
to an int
is a common task in C++ programming, especially when dealing with user input, file parsing, or network communication. While seemingly straightforward, it involves careful consideration of potential errors, such as invalid input formats or out-of-range values. This article explores several standard and safe methods to perform this conversion, ensuring your applications are robust and handle unexpected data gracefully.
Using std::stoi
(C++11 and later)
The std::stoi
function, introduced in C++11, is the most straightforward and recommended way to convert a std::string
to an int
. It automatically handles leading whitespace and can detect invalid characters, throwing exceptions for errors. It also supports an optional pos
parameter to indicate the position of the first character that was not converted, and a base
parameter for different number bases (e.g., binary, octal, hexadecimal).
#include <string>
#include <iostream>
int main() {
std::string str1 = "123";
std::string str2 = " -456";
std::string str3 = "789abc";
std::string str4 = "9999999999999999999999999999999999999999"; // Out of int range
std::string str5 = "not_a_number";
try {
int num1 = std::stoi(str1);
std::cout << "'" << str1 << "' converted to: " << num1 << std::endl;
int num2 = std::stoi(str2);
std::cout << "'" << str2 << "' converted to: " << num2 << std::endl;
size_t pos;
int num3 = std::stoi(str3, &pos);
std::cout << "'" << str3 << "' converted to: " << num3 << ", remaining: '" << str3.substr(pos) << "'" << std::endl;
// This will throw std::out_of_range
// int num4 = std::stoi(str4);
// std::cout << "'" << str4 << "' converted to: " << num4 << std::endl;
// This will throw std::invalid_argument
// int num5 = std::stoi(str5);
// std::cout << "'" << str5 << "' converted to: " << num5 << std::endl;
} catch (const std::invalid_argument& ia) {
std::cerr << "Invalid argument: " << ia.what() << std::endl;
} catch (const std::out_of_range& oor) {
std::cerr << "Out of range: " << oor.what() << std::endl;
}
return 0;
}
Example demonstrating std::stoi
with error handling.
std::stoi
calls in a try-catch
block to handle std::invalid_argument
(if no conversion could be performed) and std::out_of_range
(if the converted value would fall outside the range of an int
).Using std::stringstream
The std::stringstream
class provides an object-oriented approach to string manipulation and conversion, similar to how std::cin
and std::cout
work with standard I/O. It's a versatile option, especially useful when you need to parse multiple values from a single string or perform more complex formatting. Error checking is done by examining the stream's state flags.
#include <string>
#include <iostream>
#include <sstream>
int main() {
std::string str1 = "123";
std::string str2 = "-456.78"; // Will only read -456
std::string str3 = "abc";
int num;
// Example 1: Valid conversion
std::stringstream ss1(str1);
if (ss1 >> num) {
std::cout << "'" << str1 << "' converted to: " << num << std::endl;
} else {
std::cerr << "Conversion failed for '" << str1 << "'" << std::endl;
}
// Example 2: Partial conversion
std::stringstream ss2(str2);
if (ss2 >> num) {
std::cout << "'" << str2 << "' converted to: " << num << std::endl;
std::string remaining;
ss2 >> remaining; // Try to read remaining part
if (!remaining.empty()) {
std::cout << "Remaining string: '" << remaining << "'" << std::endl;
}
} else {
std::cerr << "Conversion failed for '" << str2 << "'" << std::endl;
}
// Example 3: Invalid conversion
std::stringstream ss3(str3);
if (ss3 >> num) {
std::cout << "'" << str3 << "' converted to: " << num << std::endl;
} else {
std::cerr << "Conversion failed for '" << str3 << "'" << std::endl;
}
return 0;
}
Converting std::string
to int
using std::stringstream
.
flowchart TD A[Start] B{Input std::string} C{Choose Conversion Method} D[std::stoi] E[std::stringstream] F{Error Handling} G[Result int] H[End] A --> B B --> C C --> D C --> E D --> F E --> F F -- Success --> G F -- Failure --> I[Report Error] G --> H I --> H
Decision flow for converting std::string
to int
.
Using std::sscanf
(C-style function)
For those familiar with C-style string manipulation, std::sscanf
(from <cstdio>
) offers another way to convert strings. It's generally less type-safe and more prone to buffer overflows if not used carefully, but it can be efficient for simple conversions. It requires converting the std::string
to a C-style string (const char*
) using .c_str()
.
#include <string>
#include <iostream>
#include <cstdio> // For sscanf
int main() {
std::string str1 = "123";
std::string str2 = "-456.78";
std::string str3 = "abc";
int num;
// Example 1: Valid conversion
if (std::sscanf(str1.c_str(), "%d", &num) == 1) {
std::cout << "'" << str1 << "' converted to: " << num << std::endl;
} else {
std::cerr << "Conversion failed for '" << str1 << "'" << std::endl;
}
// Example 2: Partial conversion (reads -456)
if (std::sscanf(str2.c_str(), "%d", &num) == 1) {
std::cout << "'" << str2 << "' converted to: " << num << std::endl;
} else {
std::cerr << "Conversion failed for '" << str2 << "'" << std::endl;
}
// Example 3: Invalid conversion
if (std::sscanf(str3.c_str(), "%d", &num) == 1) {
std::cout << "'" << str3 << "' converted to: " << num << std::endl;
} else {
std::cerr << "Conversion failed for '" << str3 << "'" << std::endl;
}
return 0;
}
Using std::sscanf
for string to integer conversion.
std::sscanf
is generally less safe and less idiomatic C++ than std::stoi
or std::stringstream
. It doesn't throw exceptions and requires careful handling of return values to detect errors. Prefer std::stoi
for modern C++.Performance Considerations
For most applications, the performance difference between std::stoi
and std::stringstream
will be negligible. std::stoi
is often slightly faster because it's a specialized function. std::stringstream
involves object creation and stream operations, which can incur a small overhead. std::sscanf
can be fast but comes with the aforementioned safety concerns. When performance is absolutely critical and you're processing millions of conversions, benchmarking with your specific data might be necessary, but for typical use cases, readability and safety should take precedence.