You have a critical misunderstanding here that is causing this problem to not make any sense.
A number is a number. A number cannot be hexadecimal, octal, decimal, binary, or whatever. It just is what it is.
What
can change, is the
textual representation of that number. IE: how we display that number though text.
Example:
seventeen
17
0x11
%00010001
|
These are all different ways to print
the same number through text.
In C++, if you have an integer... then there is no text involved. So there is nothing to convert. If your int contains 15, then it contains 15. There's nothing more to it.
What matters here is how the number 15 gets printed to the user. Do you print it as "15"? Or as "0x0F"? Or as "fifteen"? Or what?
The other side of this coin is that the user is giving their input in the form of text as well. They can't input a number... they can only input text. So there's also a translation from text to number that cin is doing when it gets the input from the user.
So there's really
2 conversions here:
1) Converting the user's input (text) to a number (int)
2) Converting the resulting number (int) back to text
The number itself never changes. The only thing you're doing is converting to/from text in different ways.
The first conversion is happening here:
1 2
|
int num;
cin >> num; // <- this is already wrong
|
This is wrong because, by default, cin is going to assume the user is inputting a number in decimal and will convert accordingly.
Fortunately, cin knows all about hexadecimal text... so to tell it the user is inputting something in hex, you just have to give it a qualifier:
1 2 3 4 5
|
#include <iomanip> // add this to your includes
//..
int num;
cin >> hex >> num; // get the number, but convert the text as if it were in hex
|
So really... this problem is very simple:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <iostream>
#include <iomanip>
int main()
{
cout << "Please insert a number in hexadecimal: ";
int num;
cin >> hex >> num;
cout << "Your number in decimal is: " << num << endl;
return 0;
}
|
That's it.
Now if this is a school assignment... then you probably can't use the hex qualifier like that, since that'd be too easy.
So instead... you'll have to convert the text to a number yourself.
This means, you cannot use cin to do the conversion. Which means you must read a
string from cin to get the input:
1 2 3 4 5
|
string input;
cin >> input;
// ... then examine characters from the string one at a time
// so you can convert the number they typed in
|