Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - error while using atoi

Tags:

c++

atoi

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?

like image 391
Simon Avatar asked Nov 20 '12 10:11

Simon


3 Answers

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:

  • std::stoi, std::stol, std::stoll

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.

like image 181
Nawaz Avatar answered Nov 09 '22 19:11

Nawaz


There are already good answers recommending the C++ APIs of std::stoi and boost::lexical_cast.

atoi() is a C API, and broken even in C because you can't tell failure apart from a successful parse of zero. If you're writing C, use strtol() and friends instead if you care about errors, because it reports them out-of-band in ERRNO.

like image 20
pndc Avatar answered Nov 09 '22 21:11

pndc


Because the number in 001_ is 1, why should it return 0? If you want to only process one character, just use isdigit(s[0]) and s[0]-'0'. If you want better error checking to see how much of the string contains digit, use strtol.

like image 1
Michael Krelin - hacker Avatar answered Nov 09 '22 21:11

Michael Krelin - hacker