14

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?

Nawaz
  • 353,942
  • 115
  • 666
  • 851
Simon
  • 4,999
  • 21
  • 69
  • 97
  • `atoi` converts `string` to `int`. Not `int` to `string` as you said. – Maroun Nov 20 '12 at 10:09
  • possible duplicate of [How do I tell if the c function atoi failed or if it was a string of zeros?](http://stackoverflow.com/questions/1640720/how-do-i-tell-if-the-c-function-atoi-failed-or-if-it-was-a-string-of-zeros) – EvilTeach Nov 20 '12 at 10:14

4 Answers4

20

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.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
2

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.

pndc
  • 3,710
  • 2
  • 23
  • 34
1

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.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
0

atoi is kind of old ... there's a better replacement in boost lib " lexical cast ".

char * str = boost::lexical_cast<std::string>(int_value);

or

int int_value = boost::lexical_cast<int>(string_value);
Alireza Soori
  • 645
  • 9
  • 25