/*-----------------------------------------------------
写一个函数atoi(const char*),它以一个包含数字的C风格字符串为参数,
返回与之对应的int值. 例如, atoi("123")应是123. 修改atoi(), 使
之除了能处理简单的十进制数之外, 还能处理C++的八进制和十六进制记法形式.
修改atoi()以处理C++的字符常量记法.
-----------------------------------------------------*/
#include <iostream>
#include <string>
#include <math.h>
using std::cout;
using std::cin;
using std::endl;
using std::string;
const int N = 20;
char* create()
{
cout << "Please input a string of numbers(0~9):\n";
char* cch = new char[N];
int i = 0;
char ch;
for (; i < N-1; i++)
{
ch = cin.get();
if (ch != '\n')
cch[i] = ch;
else
break;
}
cch[i] = '\0';
return cch;
}
void show(char* sch)
{
cout << "Output the string:\n";
puts(sch);
}
int atoi(char* ach)
{
cout << "Converts a string to an integer:\n";
int anum = 0;
int l = strlen(ach);
for (int i = 0; i < l; i++)
anum += (ach[i]-48) * pow(10, l-i-1);
cout << "How do you want to output the number(oct、dec or hex):\n";
string str;
cin >> str;
if (str == "oct")
cout << std::oct;
else if (str == "hex")
cout << std::hex;
else
cout << std::dec;
return anum;
}
int main()
{
int num;
char *ch;
ch = create();
show(ch);
num = atoi(ch);
cout << num << endl;
return 0;
}