做题的时候碰到了这个,要求把字符串里的字符数字转换为数字输出出来,而且要对8进制和16进制的输入进行处理,
我们假设输入都是正规的数,即:
十进制不是以0开头的,
八进制是以前缀0开头的,
十六进制是以前缀0x或0X开头的;
下面贴上代码:
#include <iostream>
#include <cctype>
#include <cstdlib>
#include <cmath>
using namespace std;
int My_atoi(char * str)
{
int number = 0;
int sig = 1;
if(*str == '-')
{
sig = -1;
++str;
}
char * s1,* s2;
s1 = s2 = str;
if(*s1 != '0')
{
cout << "检测到输入为十进制数:\n";
while(*str != '\0')
number = number * 10 + *str++ - '0';
}
if(*s1 == '0' && *(++s1) != 'x' && *s1 != 'X')
{
cout << "检测到输入为八进制数:\n";
while(*s1 != '\0')
number = number * 8 + *s1++ - '0';
}
if(*s2 == '0' && (*(++s2) == 'x' || *s2 == 'X'))
{
cout << "检测到输入为16进制数:\n";
char *pc1, *pc2;
pc1 = pc2 = ++s2;
while(*pc1 != '\0')
{
if(isdigit(*pc1))
{
number = number * 16 + *pc1 - '0';
}
if(isalpha(*pc1))
{
number = number * 16 + *pc1 - '0' - 39;
}
++pc1;
}
}
return number * sig;
}
int main()
{
char a[30];
cout << "Enter your string value\n";
while(cin.getline(a, 30))
{
int x = My_atoi(a);
cout << "The number in the string is " << x << endl;
cout << "Enter next string values: \n";
}
return 0;
}