strToInt

3211 ワード

テスト:
struct TestInput
{
    const char* str;
    int expectedRetValue;
    int expectedErrStatus;
} ;
TestInput inputs[] =
{
    {"123", 123, kValid},
    {"+123", 123, kValid},
    {"-123", -123, kValid},
    {" 123", 123, kValid},
    {"123abc", 123, kValid},
    {"123.", 123, kValid},
    {NULL, 0, kInvalid},
    {"", 0, kInvalid},
    {"+", 0, kInvalid},
    {"-", 0, kInvalid},
    {".123", 0, kInvalid},
    {"abc", 0, kInvalid}
};
#include 
#define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))
void testStrToInt()
{
    int failed = 0;
    unsigned int i = 0;
    for (i=0; i

実装:
#define NULL 0
typedef enum
{
    kValid,
    kInvalid
} ErrorStatus;
ErrorStatus g_error_status = kInvalid;
static bool isDigit(char c)
{
    return !((c-'0') < 0 || (c-'0') >9);
}
static bool isWhiteSpace(char c)
{
    return ((c == '\t') || (c == ' '));
}
static bool overflowForIntType(bool minus, long long num)
{
    return ( (minus && num < (signed int)0x80000000)
             || (!minus && num > 0x7fffffffL));
}
static const char* ignoreWhitespace(const char* str)
{
    while(*str && isWhiteSpace(*str))
    {
        str++;
    }
    return str;
}
/*
should pass below test cases:
|----------------------------
|input		|return	|g_error_status
|----------------------------
|123		|123	|kValid
|----------------------------
|+123		|123	|kValid
|----------------------------
|-123		|-123	|kValid
|----------------------------
|[blank]123	|123	|kValid
|----------------------------
|[tab]123	|123	|kValid
|----------------------------
|123abc		|123	|kValid
|----------------------------
|123.		|123	|kValid
|----------------------------
|[null]		|0		|kInvalid
|----------------------------
|""			|0		|kInvalid
|----------------------------
|+			|0		|kInvalid
|----------------------------
|-			|0		|kInvalid
|----------------------------
|.123		|0		|kInvalid
|----------------------------
|abc		|0		|kInvalid
|----------------------------
*/
int strToInt(const char* str)
{
    g_error_status = kInvalid;
    if ( (NULL == str) || (*str == '\0'))
    {
        return 0;
    }
    
    const char* cur = ignoreWhitespace(str);
    bool minus = false;
    if (*cur == '-')
    {
        minus = true;
        ++cur;
    }
    else if (*cur == '+')
    {
        ++cur;
    }
    
    long long result = 0;
    bool isNum = false;
    while((*cur != '\0'))
    {
        if (!isDigit(*cur))
        {
            break;
        }
        else
        {
            isNum = true;
            result = result*10 + (*cur - '0') ;
        }
        cur++;
    }
    
    if (!isNum)
    {
        return 0;
    }
        
    if (minus)
    {
        result = -1*result;
    }
    if (overflowForIntType(minus, result))
    {
        return 0;
    }
    
    g_error_status = kValid;
    return (int)result;
}