【C语言】模拟实现一个atoi将字符串转换成整形的函数

源码:

#include<stdio.h>
#include<Windows.h>
#include<iostream>
#include<string>
#include<vector>
#include<assert.h>
using namespace std;
#pragma warning(disable:4996)

enum Status
{
    ERR,
    OK,
};

Status status = OK;

/*
  字符串转换成整数,需要考虑以下几种情况:
  1.字符串中包含空格
  2.字符串中包含除数字字符外的其他字符
  3.字符串中包含正负号
  4.考虑整形数据的溢出问题

*/
int my_atoi(const char *str){
    assert(str);
    int flag = 1;//flag = 1 -->  正数   flag = -1 -->  负数
    long long sum = 0;//防止溢出

    //处理空格
    while (isspace(*str)){
        str++;
    }
    if ('\0' == *str){
        status = ERR;
        return 0;
    }

    //处理正负号
    if ('-' == *str){
        flag = -1;
        str++;
    }
    else if ('+' == *str)
        str++;

    //字符串转整形
    while (isdigit(*str)){
        sum = sum * 10 + (flag*(*str - '0'));

        //整形溢出
        if (sum > INT_MAX || sum < INT_MIN){
            status = ERR;
            return -1;
        }

        str++;
    }
    if ('\0' == *str){
        return (int)sum;
    }
    //字符串中包含其他字符
    status = ERR;
    return (int)sum;

}

int main(){


    //char *str = "1234";
    //char *str = "-1234";
    //char *str = "-12345678923456776732874386582";
    //char *str = "-12a34";
    char *str = "  ";
    int ret = my_atoi(str);
    if (OK == status){
        cout << "success: " << ret << endl;
    }
    else{
        cout << "failed: " << ret << endl;
    }

    system("pause");
    return 0;
}

程序运行结果:

“1234”
这里写图片描述

带符号字符串:“-1234”

这里写图片描述

整形溢出:”-12345678923456776732874386582”

这里写图片描述

其他字符:”-12a34”

这里写图片描述

空字符串:“ ”

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值