这个stoi程序,限于本人水平,这个可能存在设计比较垃圾的问题
该程序能够做到字符串转10进制整型,8进制,16进制,可以根据输入绝对
具有纠错 I ,O o三个字符错误的功能,和判断所转字符串格式对错的功能
可能有很多漏洞,但是能够执行,希望各位看官多多纠正
头文件
typedef enum { ok = 1, error = 0 }status;
status judge_sign(char *str, int *result);//使用接口
.cpp文件
#include"a_to_i.h"
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string>
#include<limits.h>
#include <ctype.h>
#include<stdlib.h>
#include<assert.h>
using namespace std;
int Dec_num(char *str);
int Hex_num(char *str);
int Oct_num(char *str);
int chose_fun(char *str);//选择进制
int cross_range(long long val);//是否越界
bool error_correction(char &ch);//纠错
status judge_sign(char *str, int *result)
{
assert(str != NULL);
char sign = '+';
char *p = str;
switch (*p)
{
case '+':p++; break;
case '-':sign = '-'; p++; break;
case ' ':p++; judge_sign(p, result); break;
default:break;
}
error_correction(*p);
if (isdigit(*p))
{
*result = (sign == '+') ? chose_fun(p) : -chose_fun(p);
return ok;
}
else return error;
}
int chose_fun(char *str)
{
assert(str != NULL);
char *p = str;
int num;
if (*p == '0')
{
if (*(p+1) == 'x')
{
num = Hex_num(p+2);
}
else num = Oct_num(p);
}
else num = Dec_num(p);
return num;
}
int Oct_num(char *str)
{
char *p = str;
char *q = p;
int num=0;
while (*p != '\0')
{
if (!error_correction(*p)&&!isdigit(*p) || *p > '7')
{
break;
}
p++;
}
while (q != p)
{
num = cross_range((*q - '0')*pow(8, p - q - 1) + num);
q++;
}
return num;
}
int Dec_num(char *str)
{
char *p = str;
char *q = p;
int num = 0;
while (*p != '\0')
{
if (!error_correction(*p) && !isdigit(*p))
{
break;
}
p++;
}
while (q != p)
{
num = cross_range((*q - '0')*pow(10, p - q - 1) + num);
q++;
}
return num;
}
int Hex_num(char *str)
{
char *p = str;
char *q = p;
int num = 0;
while (*p != '\0')
{
if (!error_correction(*p) && !isxdigit(*p))
{
break;
}
p++;
}
while (q != p)
{
tolower(*q);
num = cross_range((*q - '0')*pow(16, p - q - 1) + num);
q++;
}
return num;
return 0;
}
int cross_range(long long val)
{
if (val > INT_MAX)
return INT_MAX;
else if (val < INT_MIN)
return INT_MIN;
else return val;
}
bool error_correction(char &ch)
{
int i = 0;
char error_ch[3] = { 'I', 'O', 'o' };
for (; i < 3; i++)
{
if (ch == error_ch[i])
{
cout << error_ch[i] << "是否输错,修改按y" << endl;
char x;
cin >> x;
if (x == 'y')
{
if (i == 0)
{
ch = '1';
}
else ch = '0';
return true;
}
}
}
return false;
}
main函数
#include"a_to_i.h"
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string>
#include<limits.h>
#include <ctype.h>
#include<stdlib.h>
#include<assert.h>
using namespace std;
void main()
{
while (1)
{
char x[100];
system("cls");
cout << "输入字符串"<<endl;
cin >> x;
int result = 0;
if (judge_sign(x, &result) == ok)
{
cout << result << endl;
}
else cout << "number error" << endl;
char y;
cout << "是否继续:y/n" << endl;
cin >> y;
if (y == 'n')
{
break;
}
}
}