The function has many return statements that do not make sense as for example
return sign; // if sign start with charcter
And your function returns either sign or 0. In fact it does not take into account the sign of the stored value in the string.
Also take into account that the string can contain leading or trailing white space characters.
You could implement the function the same way.as standard C function strtol
. A simplified function can ignore the case when the stored number is too big to fit in an object of the type int
.
Here is a demonstration program that shows how the function can be implemented.
#include <ctype.h>
#include <stdio.h>
int StringToInteger( const char *str )
{
const int Base = 10;
int sign = 0;
while (isspace( ( unsigned char )*str )) ++str;
if (*str == '-' || *str == '+')
{
if (*str == '-') sign = 1;
++str;
}
int value = 0;
for (unsigned char c = *str; isdigit( c ); c = *++str )
{
int digit = c - '0';
value = Base * value + ( sign ? -digit : digit );
}
while (isspace( ( unsigned char )*str )) ++str;
return *str == '\0' ? value : 0;
}
int main( void )
{
const char *str = " -12345\t";
printf( "\"%s\" = %d\n", str, StringToInteger( str ) );
str = " 12345\t";
printf( "\"%s\" = %d\n", str, StringToInteger( str ) );
str = " 12345\tA";
printf( "\"%s\" = %d\n", str, StringToInteger( str ) );
str = " @12345\t";
printf( "\"%s\" = %d\n", str, StringToInteger( str ) );
str = " 123@45\t";
printf( "\"%s\" = %d\n", str, StringToInteger( str ) );
}
The program output is
" -12345 " = -12345
" 12345 " = 12345
" 12345 A" = 0
" @12345 " = 0
" 123@45 " = 0