Tuesday, August 08, 2006

Don't use atoi( )

If atoi() is used for converting any command line based input, there is a good chance that your program interprets the data incorrectly. atoi(), doesn't detect errors. The following example show what does it means

#add2total -name shyam -score xyz --> eg.1
#add2total -name shyam -score 1xyz --> eg.2
#add2total -name shyam -score 1x2yz -->eg.3

"add2total" takes two arguments; name of the player and runs (or score) of the player. Score is always expected to be >= 0.

atoi() returns 0, if the first character is not an integer value. Else, it reads the valid integer characters till a non valid character is found or till the end of the input. In case of eg.1, atoi() returns 0 for the score "xyz". In case of ex.2 and 3, it reurns a value 1.

Whats the problem?

When a value 0 is received from atoi(), our program cann't determine whether the input was indeed a "0" or an invalid input. Use the following method to overcome this problem.


static bool isValidNum( const char *numStr )
{
if( numStr == NULL )
{
return false;
}

unsigned int len = strlen( numStr );

if( len == 0 )
{
return false;
}

for( unsigned int i = 0; i < len; i++ )
{
if( (numStr[i] < '0') || (numStr[i] > '9') )
{
return false;
}
}

return true;
}