把字符串转换成整数,考虑空,非法字符,溢出

本文深入探讨了从字符串转换为整数时可能遇到的各种问题,包括空串、空指针、非法字符和整数溢出等,并提供了一个详细的C++实现示例,帮助读者理解并解决这些常见问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目要求

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

注意的问题

  • 字符串为空串或空指针.
  • 字符串含有非0到9的字符.
  • 特别注意字符串转换到int值,要考虑溢出的问题,正整数的最大值是0x7FFFFFFF (2147483647),负数的最小值是0x80000000(-2147483648).

 

#include <iostream>
#include <string.h>
using namespace std;

const int  MAX = 2147483647;
const int  MIN = -2147483648;
bool strToInt(const char *str,int &numInt)
{
    numInt = 0;

    if(str == NULL) {
        std::cout<<"空指针"<<endl;
        return false;
    }
    else if(str == "") {
        cout<<"空串"<<endl;
        return false;
    }
    else {
        const char *p =str;
        bool isFist = true;
        bool hasMinus = false;

        while(*p != '\0') {
            if (isFist && *p == '-') {
                hasMinus = true;
                p++;
                continue;
            } else if (isFist && *p == '+') {
                hasMinus = true;
                p++;
                continue;
            }

            if ((*p) >= '0' && (*p) <= '9') {

                numInt = numInt*10 + *p-'0';
                if( (!hasMinus && numInt > MAX/10) || (hasMinus && numInt < MIN/10) )
                {
                    cout<<"存在整数溢出!"<<endl;
                    return false;
                }
                p++;
            }
            else {
                cout<<"存在非法字符"<<endl;
                return false;
            }
        }
        if(hasMinus) {
            numInt *= (-1);
        }

        return true;
    }
}

int main() {

    int numInt = 0;
    char *str = NULL;

   

    if(strToInt("123",numInt))
    {
        printf("%d\n",numInt);
    }

    if(strToInt("",numInt))
    {
        printf("%d\n",numInt);
    }

    if(strToInt(str,numInt))
    {
        printf("%d\n",numInt);
    }

    if(strToInt("+123",numInt))
    {
        printf("%d\n",numInt);
    }

    if(strToInt("-123",numInt))
    {
        printf("%d\n",numInt);
    }

    if(strToInt("-#45600@3#",numInt))
    {
        printf("%d\n",numInt);
    }

    if(strToInt("1004324230000000000000000000000000",numInt))
    {
        printf("%d\n",numInt);
    }

    if(strToInt("-100003424300000000000000000000000",numInt))
    {
        printf("%d\n",numInt);
    }


    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值