写出一个程序,接受一个十六进制的数值字符串,输出该数值的十进制字符串。(多组同时输入 )
输入描述:
输入一个十六进制的数值字符串。
输出描述:
输出该数值的十进制字符串。
输入例子1:
0xA
输出例子1:
10
//最开始写的
#include<iostream>
#include <math.h>
#include <string>
#include <vector>
using namespace std;
int main()
{
string str;
while (cin >> str)
{
if (str[0] == '0' && str[1] == 'x')
{
string newStr;
auto it = str.begin() + 2;
while (it != str.end())
{
newStr.push_back(*it);
it++;
}
str.clear();
reverse(newStr.begin(), newStr.end());
vector<int> ivec;
it = newStr.begin();
while (it != newStr.end())
{
if (*it >= '0' && *it <= '9')
{
ivec.push_back((*it - '0'));
}
else if (*it >= 'A' && *it <= 'F')
{
ivec.push_back((*it - 'A') + 10);
}
else if (*it >= 'a' && *it <= 'f')
{
ivec.push_back((*it - 'a') + 10);
}
++it;
}
int sum = 0;//数值型局部变量要赋初值!!!
for (int i = 0; i<ivec.size(); ++i)
{
sum += ivec[i] * (int)(pow(16, i));
}
cout << sum << endl;
}
}
return 0;
}
//改进
#include<iostream>
#include <math.h>
#include <string>
#include <vector>
using namespace std;
int main()
{
string str;
while (cin >> str)
{
if (str[0] == '0' && str[1] == 'x')
{
string newStr = str.substr(2);
vector<int> ivec;
int sum = 0;//数值型局部变量要赋初值!!!
auto it = newStr.begin();
while (it != newStr.end())
{
int temp = 0;
if (*it >= '0' && *it <= '9')
{
temp = *it - '0';
}
else if (*it >= 'A' && *it <= 'F')
{
temp = *it - 'A' + 10;
}
else if (*it >= 'a' && *it <= 'f')
{
temp = *it - 'a' + 10;
}
sum = sum * 16 + temp;
++it;
}
cout << sum << endl;
}
}
return 0;
}