Sunday, October 14, 2012

Transfer string to int type


Transfer string to int type

//need consider '+', '-' sign
//need consider overflow
//need consider illege characters

#include <iostream>
#include <limits>

using namespace std;

bool returnflag;

int StrToInt(const char *str)
{
    long long num = 0;
    if(NULL == str)
        returnflag = FALSE;
    if(NULL != str)
    {
       if(*str =='+' || *str=='-')
       {
           int minus=0;
           if(*str=='-')
               minus = 1;  
       }
     
      while(*str!='\0')
      {
           if(*str >= '0' && *str<='9')
           {
               num= num*10+*str-'0';
             
               if(num > numeric_limits<int>::max())
               {
                   break;
                   return 0;
               }
           }
           str++;  
       }
     
       if(*str=='\0')
       {
           returnflag = TRUE;
           if(minus)
               num = 0-num;
       }
               
    }
 
    return static_typecast<int>(num);
}

No comments:

Post a Comment