开发者

trying to make a C++ program to convert a 4 digit octal number to decimal

开发者 https://www.devze.com 2023-02-24 10:35 出处:网络
This here is my code, I have tried googling it but i can find why my code doesnt convert the number properly. however it complies fine. could you please tell me why it is not working and what i should

This here is my code, I have tried googling it but i can find why my code doesnt convert the number properly. however it complies fine. could you please tell me why it is not working and what i should do to fix it.

#include <iostream> 
using namespace std; 

int main() 
{ 
    char a = 0; 
    char b = 0; 
    char c = 0; 
    char d = 0;

    cout << "Enter 4 digit oct开发者_开发百科al number "; 
    cin >> a >> b >> c >> d; 

    cout << "Decimal form of that number: " << (a * 512) + (b * 64) + (c * 8) + d << endl; 

    return 0; 

}


Because you're getting the values as characters, they're probably ascii values that you're multiplying with. Try using (a-'0'), (b-'0'), etc.

You also should validate your input to be sure it's a number from 0 to 7.


Why not let the standard library do the work?

#include <ios>
#include <ostream>
#include <iostream>

int main()
{
    unsigned n;
    std::cin >> std::oct >> n;
    std::cout << n << std::endl;
}


convert your values (a, b, c, d) to integers, then multiply.

0

精彩评论

暂无评论...
验证码 换一张
取 消