#include <string>
#include <iostream>
using namespace std;
// Convert an octal number as a string to int
int oct2int(string str) {
int x = 0;
for (int i=0; i<str.length(); i++) {
int d = str[i] - '0';
if (d < 0 || d > 7)
return -1;
x *= 8;
x += d;
}
return x;
}
// Convert a nonnegative integer to string
string int2dec(int x) {
string res;
if (x == 0) {
res = '0';
}
while (x != 0) {
int d = x % 10;
res = static_cast<char>(d + '0') + res;
x /= 10;
}
return res;
}
int main() {
string oct[] = { "0111",
"1777",
"2345",
"1234",
"7654" };
for (int i=0; i<5; i++) {
cout << oct[i] << " octal is equal "
<< int2dec(oct2int(oct[i]))
<< " decimal" << endl;
}
return 0;
}
Comments
Leave a comment