trying to make a C++ program to convert a 4 digit octal number to decimal
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.
精彩评论