Search code examples
c++stringatoi

C++ How to convert string, which has string and numeric, into int or long


I'm trying to convert a string variable, which contains alphabetic and numeric values, into an int variable.

string argument = "100km";
int i = atoi(argument.c_str());
cout<<i<<endl;

I've confirmed that i has an int of 100 and km is omitted. However, if I enter 2147483648km, which is over that range of int, i will have -2147483648.

According to this page, int is supposed to be able to have

–2,147,483,648 to 2,147,483,647

So, I thought that this error came from the range of int, but the same error happens even when atoi is replaced by atol and int is replaced by unsigned long, which can have a much larger value. In other words, replacing int with long doesn't fix this error.

Chances are that I need to come up with an alternative way to convert this kind of string (i.e. string of "______km" into an int variable).


Solution

  • The data type ranges from Microsoft's site can show you what Visual C++ compilers use.
    This may vary, see 6502's answer covering that.

    Moreover, atol returns a long, so if you give it a unsigned long you're going to get a long in return.

    Since C++11, you are able to use atoll which returns a long long, otherwise see the other answers using stoi, stol, stoll.