#include <limits.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
static int isspace(int c)
{
return (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v');
}
int Danny_Atoi(char *SrcString)
{
char *IterIndex = SrcString;
int RetVal = 0;
int SignedNegative = 1;
int int_bound = INT_MAX /10;
int Len= strlen(SrcString);
while ( isspace( *IterIndex ) )
{
IterIndex ++;
printf("NULL SPACE...Continue....\n");
continue;
}
if ( '-' == *IterIndex )
SignedNegative = -1;
int i =0;
while( !isdigit (*IterIndex) && int_bound && i<Len )
{
printf("Skip a non-digit: %c...\n", *IterIndex);
IterIndex ++;
i ++;
}
while ( isdigit( *IterIndex ) && int_bound )
{
printf("A digit Found:%c...\n", *IterIndex);
RetVal = RetVal*10 + (*IterIndex - '0');
int_bound/=10;
IterIndex ++;
}
if ( -1 == SignedNegative )
{
printf("The String you input is negative........\n");
RetVal*= -1;
}
if (!int_bound)
{
printf("OverFlow Number.....\n");
return -1;
}
return RetVal;
}
int main( int argc, char **argv )
{
if (argc <= 1)
{
printf("Please Provide Your String that you want to convert....\n");
return 0;
}
int RetVal;
RetVal = Danny_Atoi ( argv[1] );
if ( 0 == RetVal )
{
printf("No Number found in the input string.....\n");
}
else if ( -1 == RetVal )
{
printf("IntGer OverFlow....\n");
}
else
{
printf("Congratulations..Number is:%d..\n", RetVal);
}
return 0;
}
编译:# gcc -g -o Atoi Atoi-implementation.c
异常运行结果:
# ./Atoi
Please Provide Your String that you want to convert....
正常运行结果:
# ./Atoi get123get
Skip a non-digit: g...
Skip a non-digit: e...
Skip a non-digit: t...
A digit Found:1...
A digit Found:2...
A digit Found:3...
Congratulations..Number is:123..