Answer to Question #148187 in C++ for Arslan khan

Question #148187
Write a c++ programe to convert 5 octal number into decimal
1
Expert's answer
2020-12-01T13:00:05-0500
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog