Last updated:2026-10-12
C++ string to int¶
My WeChat official account:

First, here are the candidate solutions:
- atoi
- strtol
- stoi
What are the differences between these? Let's compare them with tests below.
C-style functions
Comparing atoi and strtol:
Output:
Both of these functions start scanning the string for digits, a sign, or a decimal point, and stop when an invalid character is encountered.
That is why scanning stops early at the "s" character above — in other words, when your string is not a number, or contains a decimal point or other non-digit characters, no exception is thrown! It simply outputs 0.
For example:
Output:
Compared with atoi, strtol supports conversion with multiple bases, such as base 8.
For example:
C++ style
In C++, you can use stoi to convert to int. The single biggest characteristic of this function compared with the previous two is: exceptions!
As we know, C++ adds exceptions compared to the C language, and this is the most prominent capability this function gains in C++.
For example:
string str1 = "asq,";
// int c = stoi(str1); // 报异常
string str2 = "12312";
int c = stoi(str2); // ok
cout << c << endl;
The exception is as follows:
Roll your own
That is, write it yourself, as follows:
int stringToInt(const string &s) {
int v;
stringstream ss;
ss << s;
ss >> v;
return v;
}
int main() {
int i = stringToInt("2.3");
cout<<i<<endl;
}
Related Topics¶
- Building C++ Projects with Bazel | C++那些事
- Debugging Bazel Builds with LLDB | C++那些事
- CMake Essentials in Practice | C++那些事
- Getting Started with the Conan C++ Package Manager | C++那些事
- C++ Insights Compile-Time Observation | C++那些事
- Interactive C++ in Jupyter Notebook | C++那些事
- The C++ dbg-macro Debugging Macro | C++那些事
- GCC Compilation Flags Explained | C++那些事
- Debugging C++ Programs with GDB | C++那些事
- GDB Python Extension Debugging | C++那些事