准完美的atoi函数实现

#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..


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值