Skip to content

Last updated:2026-10-12

C++ string to int

My WeChat official account:

wechat

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:

string str = "16s";
int a = atoi(str.c_str());
int b = strtol(str.c_str(), nullptr, 10);

Output:

atoi的结果为:16
strtol的结果为:16

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:

string str = "asdsa";
int a = atoi(str.c_str());
int b = strtol(str.c_str(), nullptr, 10);

Output:

0
0

Compared with atoi, strtol supports conversion with multiple bases, such as base 8.

For example:

int b = strtol(str.c_str(), nullptr, 8);

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:

terminate called after throwing an instance of 'std::invalid_argument'
what():  stoi

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;
}

Comments