Помогите найти ошибку в функции перевода
Нужно осуществить перевод из 7ой системы счисления в десятичную. Вводил число я в виде строки, после чего переводил в число. Но на моменте перевода в 10ую систему мне выдает по итогу мусор вместо 69 В чем ошибка?
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
int size(string str)
{
int i = 0;
while (str[i] != '\0')
{
i++;
}
return i;
}
int atoi(string str, int a)
{
int x=0;
for (int i = 0; i < size(str); i++)
{
a=x += (int(str[i]) - int('0')) * pow(10, (size(str) - i) - 1);
}
return a;
}
int translaterIn10(string str, int a, int arr[])
{
int i = 0;
while (a / 10 != 0)
{
arr[i] = a % 10;
a /= 10;
i++;
}
//arr[i]=6, 2, 1;
//6 * 7^0 + 2 * 7^1 + 1 * 7^2=69;
int c=0;
for (int i = 0; i < size(str); i++)
{
c += arr[i]*pow(7, i);
}
return c;
}
int main()
{
string str1;
int *arr = new int[size(str1)];
int a=0;
cout << "Enter your number in sevenfold number system:\n";
cin >> str1;
cout << "Your number in sevenfold number system:\n" << str1 << endl;
atoi(str1, a);
cout<<"Your number in decimal system:\n"<<translaterIn10(str1, a, arr);
delete[] arr;
return 0;
}
Ответы (1 шт):
Автор решения: Harry
→ Ссылка
И в самом деле, зачем просто, если можно сложно?...
string s;
cin >> s;
int x = 0;
for(const char * c = s.c_str(); *c; ++c) x = x*7 + (*c - '0');
cout << x;
Если даже c_str() слишком стандартная :), то
string s;
cin >> s;
int x = 0;
for(const char * c = &s[0]; *c; ++c) x = x*7 + (*c - '0');
cout << x;