如何将字符串转换为相应的整型

来源:互联网 发布:淘宝发帖怎么发求链接 编辑:程序博客网 时间:2024/06/05 23:46

将字符串转换为整型: 

 

 

bool IsDigit(char c)

{

return (c >= '0')&&(c <= '9');

}

 

bool IsAlpha(char c)

{

return ((c >= 'a')&&(c <= 'z')) || ((c >= 'A')&&(c <= 'Z'));

}

 

bool IsAlphaOrDigit(char c)

{

return (IsDigit(c) || IsAlpha(c));

}

 

unsigned long str2int(const char* source, unsigned long& Base )

{

unsigned long result = 0;

unsigned long value = 0;

const char* temp = source;

Base = 10;

 

//check whether is valid

if (IsAlphaOrDigit(*temp))

{

//check the type

if (*temp == '0' )

{

if ( (temp[1] == 'x') || (temp[1] == 'X') )

{

Base= 16;

temp += 2;           

}else{

Base = 8;

temp++;

}

}

 

        while ( IsAlphaOrDigit(*temp))

        {

value = IsDigit(*temp) ? *temp - '0' : *temp - 'A' + 10;

result = result*Base + value;

++temp;

}

 

if (*temp != '/0')

{

//error

std::cout << "not valid string" << std::endl;

return -1;

}

 

return result;

 

}else{

//error,not valid string

std::cout << "not valid string" << std::endl;

return -1;

}

 

}

 

long str2int_signed(const char* source, unsigned long& Base)

{

if (*source == '-')

return -str2int(source+1,Base);

 

return str2int(source,Base);

}

 

代码经过测试和运行。

原创粉丝点击