打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

http://blog.csdn.net/bichenggui/article/details/4255475

2009

将字符串转换为整型: 

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);

}

 

代码经过测试和运行。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
有关数据类型转换
sqlserver实现分隔字符串
C语言字符串,字符转数字,数字转字符(转)
字符型
单片机C语言程序设计基础知识全解析
从语言char数据类型
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服