Click here to Skip to main content
15,881,898 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
Hi,

I came across C++ function
atoi
, This function returns integer representation of given string.

If i pass "987" to this function , it will return 987 as integer.

In MSDN it is written that, this function returns 0 on failure. What if i pass "0" to this function ??

it will return 0 as integer .....Should i treat it as a ERRORCODE or converted value :(
Posted
Comments
Eugen Podsypalnikov 21-Jun-12 6:54am    
// In MSDN it is written that, this function returns 0 on failure.

Please try it :) :
assert(12 == atoi("12 months"));

When the function returns 0, you must check yourself if the string is a valid number (parse for optional leading white spaces, optional sign, and the '0' character followed by a NULL byte).

If you need advanced error checking, you may use the strtol() [^] function.
 
Share this answer
 
v2
Comments
PrafullaVedante 21-Jun-12 6:47am    
strtol also has same problem.
Jochen Arndt 21-Jun-12 6:54am    
Not when passing the endptr parameter and check if it is equal to nptr (not a number) or points to an invalid termination character (not NULL, trailing white spaces may be optional allowed). strtol also provides checks for overflow and underflow conditions via return value and errno.
nv3 21-Jun-12 8:27am    
I fully agree. For serious business, always use strtol and not atoi. +5
BillW33 21-Jun-12 10:16am    
Good answer Jochen, +5.
You can use errno global variable. If it is not equal to 0 then there was error and you can check what it was (overflow or other conversion error)
In the case atoi returns 0 and errno == 0 you can be sure that conversion was finished successfully

Something like this:
C++
int val;

val = atoi("bad value");
if (errno != 0)
{
   printf("Error");
}
else
{
   // Do something with val
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900