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
atoiis unsafe to use. It doesn’t detect and inform the program if the input is invalid.C++11 has introduced
std:stoiwhich is safe, as it throws exception if input is invalid in some way. There are also two other variants :std::stolandstd:stoll. See the online documentation for detail:std::stoi,std::stol,std::stollYour code would become this:
Note that the runtime type of
ecould be eitherstd::invalid_argumentorstd::out_of_rangedepending on the cause of the throw. You could just write twocatchblocks if you want them to handle differently.