本文讲解一种在c++中如何将16进制字符串转化成10进制,水平不高,但愿对你有帮助。一下便是源程序,包涵检错以及转化函数。前些日子帮一个朋友做笔试题,结果因为不熟悉这块的内容,只得了80分,自己好好安静下来写了一次,
#include<iostream>
#include<string>using namespace std;
void check(string s);
void change(string &s);
bool flag = true;
void main()
{
string a;
while (flag)
{
cout << "please input" << endl;
cin >> a;
check(a);
}
change(a);
}
void check(string s)//检查输入的字符是否规范
{
if (s.size() != 4)
{
cout << "input eoor" << endl;
}
else if (s[0] != '0')
{
cout << "input eoor" << endl;
}
else if (s[1]!='x'&&s[1]!='X')
{
cout << "input eoor" << endl;
}
else if (s[2]<'0'||s[2]>'f')
{
cout << "input eoor" << endl;
}
else if (s[3]<'0' || s[3]>'f')
{
cout << "input eoor" << endl;
}
else
{
flag=false;
}
}
void change( string &s)//转化函数
{
int a[2], result;
for (int i = 2; i < 4; ++i)
{
if (s[i] <= '9')
{
a[i - 2] = s[i] - '0';
}
else
{
a[i - 2] = s[i] - 'a' + 10;
}
}
result = a[0] * 16 + a[1];
cout << "the result is" << result << endl;
}
因为字符‘0’-‘9’对应的数字是30-39,所以只需将原字符减去30或者‘0’就可以得到对应数字。但是‘a’-‘f’就不一样了,‘a’-‘a’对应的是0所以要加10