面试题1----把字符串转换成整数

题目要求:

写一个函数StrToInt实现将字符串转换为整数的功能。 

需要考虑的点
  • 字符串为空串或空指针.
  • 字符串含有非0到9的字符.
  • 特别注意字符串转换到int值,要考虑溢出的问题,正整数的最大值是0x7FFFFFFF,负数的最小值是0x80000000.
代码如下:
#include<iostream>
#include<string.h>
#include<limits>
bool strToInt(const char *str,int &nInt){
    if(str == NULL){
        std::cout <<"空指针"<<std::endl;
        return  false;
    }else if(str == ""){
        std::cout << "空串"<<std::endl;
        return false;
    }else if((strcmp(str,"+") == 0) || (strcmp(str,"-") == 0)){
        std::cout << "字符串输入无效"<<std::endl;
        return false;
    }else{
        const char *p = str;
        bool isFirst = true; //标记是否为字符串的第一个字符
        bool hasMinus = false; //标记字符串的第一个字符是否是负号.
        nInt = 0;
        while(*p != '\0'){
            if(isFirst && (*p) == '-' ){
                hasMinus = true;
                p++;
                continue;
            }else if(isFirst && (*p) == '+'){
                p++;
                continue;
            }
            if((*p) >= '0' && (*p) <= '9'){
                nInt = nInt*10+*p-'0';
                if((!hasMinus && nInt > std::numeric_limits<int>::max()) || (hasMinus && nInt < std::numeric_limits<int>::min())){
                    std::cout << "字符串数值溢出,输入无效!"<<std::endl;
                    return false;
                }
                    p++;
                }else{
                    std::cout << "字符串中包含有非数字的字符,不能转换为数字"<<std::endl;
                    return false;
                }
        }
                    if(hasMinus){
                        nInt = (-1) * nInt;
                    }
                    return true;
    }
}
int main(int argc,char *argv[])
{
    int nInt = 0;
    char *str = NULL;
    if(strToInt("123",nInt)){
        std::cout << nInt<<std::endl;
    }
    if(strToInt("",nInt)){
        std::cout <<nInt<<std::endl;
    }
    if(strToInt(str,nInt)){
        std::cout <<nInt<<std::endl;
    }
    if(strToInt("-123",nInt)){
        std::cout <<nInt<<std::endl;
    }
    if(strToInt("+123",nInt)){
        std::cout <<nInt<<std::endl;
    }
    if(strToInt("-#45466@",nInt)){
        std::cout <<nInt<<std::endl;
    }
    if(strToInt("10000000000000000000000000",nInt)){
        std::cout <<nInt<<std::endl;
    }
    if(strToInt("-10000000000000000000000000",nInt)){
        std::cout <<nInt<<std::endl;
    }
   return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值