当前位置: 代码迷 >> 综合 >> C++-atoi()函数实现
  详细解决方案

C++-atoi()函数实现

热度:93   发布时间:2023-12-14 12:19:32.0

可参考:atoi()函数实现

不过需要注意:    对于 if (*str == '\0'),应该是:*str

参考atoi()函数实现写了下:

#include<bits/stdc++.h>
#include <iostream>
using namespace std;
typedef enum Ret
{VALID,INVALID
}Ret;Ret state = INVALID;int my_atoi(const char* str)
{int flag = 1;long long ret = 0;//assert(str);if (str == NULL)return (int)ret;if (*str == '\0')return (int)ret;while (*str == ' ')str++;if (*str == '\0')return (int)ret;else if (*str == '+' || *str == '-'){if (*str == '-')flag = -1;str++;}while (*str){if ((*str >= '0') && (*str <= '9')){state = VALID;ret = ret * 10 + flag * (*str - '0');str++;if (ret > INT_MAX){state = INVALID;cout << "上溢出!" << endl;return (int)INT_MAX;}if (ret < INT_MIN){state = INVALID;cout << "下溢出!" << endl;return (int)INT_MIN;}}elsereturn (int)ret;}return (int)ret;}
int main()
{//int ret = my_atoi("");//int ret = my_atoi("1213");//int ret = my_atoi("-1213");//int ret = my_atoi("123aaa");//int ret = my_atoi("-111111111111111");//int ret = my_atoi("111111111111111");string str;cin >> str;int ret = my_atoi(str.c_str());if (state == INVALID){cout << "输入非法!" << endl;}cout << "ret = " << ret << endl;return 0;}

  相关解决方案