I am trying to use the atoi
function in order to obtain conversion from string
to int
. The thing is that I have a string array which contains both integers and string values.
From what I've read, in order to get the error code from it, the function must return 0 :
string s = "ssss";
int i = atoi(s.c_str())
if (i == 0)
cout<<"error"<<endl;
end;
How should I proceed if my string value is 0
?
Another issue is with this string : string s = "001_01_01_041_00.png"
. The atoi
function returns the value 1
. Shouldn't it return 0
. Why does it return 1
?
That is why atoi
is unsafe to use. It doesn't detect and inform the program if the input is invalid.
C++11 has introduced std:stoi
which is safe, as it throws exception if input is invalid in some way. There are also two other variants : std::stol
and std:stoll
. See the online documentation for detail:
Your code would become this:
try {
string s = "ssss";
int i = std::stoi(s); //don't call c_str()
//if (i == 0) no need to check!
std::cout << i << endl;
}
catch(std::exception const & e)
{
cout<<"error : " << e.what() <<endl;
}
Note that the runtime type of e
could be either std::invalid_argument
or std::out_of_range
depending on the cause of the throw. You could just write two catch
blocks if you want them to handle differently.