In this C++ tutorial, you will learn how to convert a std::string to an int using std::stoi(), std::atoi(), std::stringstream, and std::from_chars(). You will also learn how each method handles invalid input, trailing characters, numeric bases, and values outside the range of int.
C++ String to Integer: Which Method Should You Use?
For most C++11 and later code, std::stoi() is the simplest choice when you want an integer and are comfortable handling exceptions. If you need non-throwing, low-level parsing in C++17 or later, std::from_chars() gives explicit error reporting. std::stringstream is useful when parsing formatted text, while std::atoi() is mainly a legacy C-style option with limited error reporting.
| Method | C++ version | Error handling | Useful when |
|---|---|---|---|
std::stoi() | C++11+ | Throws exceptions | You want a direct std::string to int conversion |
std::from_chars() | C++17+ | Returns an error code | You want non-throwing numeric parsing and precise control |
std::stringstream | Standard C++ | Stream state | You are already parsing formatted stream-like input |
std::atoi() | C-style API | No reliable conversion error report | You are working with legacy null-terminated character strings |
1. Convert std::string to int with std::stoi()
std::stoi() reads an integer from the beginning of a string and returns the value as an int. It is declared in the <string> header.
The existing signature below shows the wide-string overload of stoi():
int stoi (const wstring& str, size_t* idx = 0, int base = 10);
For a regular std::string, the corresponding overload has this form:
int stoi(const std::string& str, std::size_t* pos = nullptr, int base = 10);
The first argument is the string to parse. The optional second argument receives the position of the first character that was not used in the conversion. The optional third argument selects the numeric base. Base 10 is decimal, base 8 is octal, and base 16 is hexadecimal.
In the following example, we shall use stoi() function to convert a string to integer.
main.cpp
#include <iostream>
using namespace std;
int main() {
string str1 = "512";
int n = stoi(str1);
cout << n << Lendl;
}
Output
512
Program ended with exit code: 0
The intended result is 512. In production code, include <string> explicitly and use std::endl or '\n' when printing a newline.
Use the base argument in std::stoi()
Now let us take a string with some number and parse it into integer with a base of 8.
We shall pass 8 for base (third argument), and nullptr (null pointer) for idx(second argument).
main.cpp
#include <iostream>
using namespace std;
int main() {
string str1 = "512";
int n = stoi(str1, nullptr, 8);
cout << n << endl;;
}
Output
330
Program ended with exit code: 0
Explanation
512 base 8 = 5*(8*8) + 1*(8) + 2(1)
= 320 + 8 + 2
= 330
Because the string is interpreted as octal, "512" represents decimal 330. The digits must be valid for the selected base.
What std::stoi() does with decimal points and trailing text
std::stoi() does not search through the whole string for a number. It starts parsing at the beginning after any permitted leading whitespace and optional sign, then stops when it reaches a character that is not valid for the integer being parsed. This is why strings such as "3.14253" and "3523 hello" can produce integer values from their initial numeric portions.
In the following program, we have covered different such scenarios.
main.cpp
#include <iostream>
using namespace std;
int main() {
cout << stoi("3.14253") << endl; //returns only 3 leaving out the rest
cout << stoi("3523 hello") << endl; //returns number 3523
cout << stoi("568 hello 536 sks") << endl; //returns first found number 568
}
Output
3
3523
568
Program ended with exit code: 0
The third example returns 568 because that is the numeric prefix. It does not skip the text and continue searching for 536.
Detect trailing characters with the std::stoi() position argument
If your input should contain only one integer, use the position argument to find out how much of the string was consumed. This prevents an input such as "42abc" from being silently accepted as 42.
#include <iostream>
#include <string>
int main() {
std::string text = "42abc";
std::size_t pos = 0;
int value = std::stoi(text, &pos);
if (pos == text.size()) {
std::cout << "Integer: " << value << '\n';
} else {
std::cout << "Unparsed text starts at index " << pos << '\n';
}
}
Unparsed text starts at index 2
Handle invalid and out-of-range strings with std::stoi()
std::stoi() can throw std::invalid_argument when no conversion can be performed, and std::out_of_range when the parsed value cannot be represented as an int. Catch these exceptions when the string may come from a user, file, command-line argument, or other untrusted source.
#include <iostream>
#include <string>
#include <stdexcept>
int main() {
std::string text = "hello";
try {
int value = std::stoi(text);
std::cout << value << '\n';
} catch (const std::invalid_argument&) {
std::cout << "The string does not start with a valid integer.\n";
} catch (const std::out_of_range&) {
std::cout << "The value is outside the range of int.\n";
}
}
The string does not start with a valid integer.
2. Convert a C-style string to int with atoi()
std::atoi(), declared in <cstdlib>, converts a null-terminated character string to int. Unlike std::stoi(), it does not provide a reliable way to distinguish every conversion error from a valid result. For example, a returned 0 can mean either that the input represented zero or that no conversion was possible.
In the following example, we shall use atoi() function to convert a char array to integer.
main.cpp
#include <iostream>
using namespace std;
int main() {
char str[] = "512";
int n = atoi(str);
cout << n;
}
Output
512
Program ended with exit code: 0
When writing new code, include <cstdlib> explicitly. If the value is stored in a std::string, pass its C-style representation with c_str(), for example std::atoi(text.c_str()).
Let us take strings containing different values like, one having float value, the next one having a number with some text, etc.
main.cpp
#include <iostream>
using namespace std;
int main() {
cout << atoi("3.14253") << endl; //returns only 3 leaving out the rest
cout << atoi("3523 hello") << endl; //returns number 3523
cout << atoi("568 hello 536 sks") << endl; //returns first found number 568
}
Output
3
3523
568
Program ended with exit code: 0
As with std::stoi(), these examples convert the numeric prefix. However, std::atoi() is a weaker choice when you need dependable validation or overflow handling.
3. Convert a string to int with stringstream
A std::stringstream treats a string as a stream. You can extract an int with the stream extraction operator >>. Include the <sstream> header.
main.cpp
#include <iostream>
#include <sstream>
using namespace std;
int main() {
string str = "314";
int n;
stringstream(str) >> n;
cout << n;
}
Output
314
Program ended with exit code: 0
When conversion may fail, keep the stream in a named variable and test its state before using the integer.
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string text = "314";
std::stringstream ss(text);
int value;
if (ss >> value) {
std::cout << "Integer: " << value << '\n';
} else {
std::cout << "Conversion failed\n";
}
}
Integer: 314
4. Convert string to int without stoi() using std::from_chars()
If you need to convert a string to an integer without std::stoi(), C++17 introduced std::from_chars() in <charconv>. It does not throw exceptions. Instead, it returns a pointer to the first unparsed character and an error code.
#include <charconv>
#include <iostream>
#include <string>
#include <system_error>
int main() {
std::string text = "512";
int value = 0;
const char* first = text.data();
const char* last = text.data() + text.size();
auto result = std::from_chars(first, last, value);
if (result.ec == std::errc{} && result.ptr == last) {
std::cout << "Integer: " << value << '\n';
} else {
std::cout << "Invalid integer\n";
}
}
Integer: 512
The check result.ptr == last verifies that the complete string was consumed. If you intentionally allow trailing text, you can omit that particular check and inspect result.ptr instead.
C++ String-to-Integer Conversion with Negative Values and Whitespace
std::stoi() accepts leading whitespace and an optional sign, so a string such as " -42" converts to -42. std::from_chars() is stricter: it does not skip leading whitespace, so trim or validate the input before parsing if spaces are permitted by your application.
#include <iostream>
#include <string>
int main() {
std::string text = " -42";
int value = std::stoi(text);
std::cout << value << '\n';
}
-42
Common C++ String-to-Int Conversion Mistakes
- Assuming trailing text is rejected automatically:
std::stoi("42abc")can return42. Use the position argument when the whole string must be numeric. - Ignoring exceptions from std::stoi(): invalid text and values outside the
intrange need explicit handling when input is not guaranteed to be valid. - Using atoi() when validation matters:
atoi()does not give the same useful error information asstoi()orfrom_chars(). - Forgetting required headers: use
<string>forstoi(),<cstdlib>foratoi(),<sstream>forstringstream, and<charconv>forfrom_chars(). - Parsing into int when the number may be larger: consider
std::stol(),std::stoll(), or a wider integer type when the input can exceed the range ofint.
Choosing Between stoi(), atoi(), stringstream, and from_chars()
Use std::stoi() for straightforward std::string conversion in C++11 and later. Use std::from_chars() in C++17 and later when you want explicit, non-throwing parse results. Use std::stringstream when integer parsing is part of broader stream-based text processing. Prefer std::atoi() mainly when maintaining code that already works with C-style strings and its limited error reporting is acceptable.
C++ String-to-Integer Conversion Summary
In this C++ Tutorial, we learned how to convert a string to integer, in many different ways, using functions like stoi(), atoi(), stringstream(), etc., with the help of example C++ programs.
TutorialKart.com