C ++ - error when using atoi

I am trying to use the atoi function to get the conversion from string to int . The thing is, I have a string array that contains both integers and string values.

From what I read in order to get the error code from it, the function should return 0:

 string s = "ssss"; int i = atoi(s.c_str()) if (i == 0) cout<<"error"<<endl; end; 

How do I proceed if my string value is 0 ?

Another problem is with this line: string s = "001_01_01_041_00.png" . The atoi function returns 1 . If it does not return 0 . Why does it return 1 ?

+7
source share
4 answers

This is why atoi not safe to use. It does not detect or inform the program if the input is invalid.

In C ++ 11, std:stoi was introduced, which is safe because it throws an exception if the input is somehow invalid. There are also two other options: std::stol and std:stoll . See the online documentation for more details:

Your code will be as follows:

 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 execution type e can be either std::invalid_argument or std::out_of_range depending on the reason for the throw. You could just write two catch blocks if you want them to handle differently.

+12
source

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

atoi () is a C API and even broken into C, because you cannot tell about the error, except for successful analysis of zero. If you write C, use strtol () and friends if you are worried about errors because they report them out of range in ERRNO.

+2
source

Since the number in 001_ is 1, why would it return 0? If you want to process only one character, just use isdigit(s[0]) and s[0]-'0' . If you want to improve error checking to see which part of the string contains a digit, use strtol .

0
source

atoi is kind of old ... there is the best 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); 
0
source

All Articles