1

So, I'm trying to make a basic C++ program that converts Base 10 -> Base 16

while(true){
    int input;
    cout << "Enter the base 10 number\n";
    cin >> input;
    cout << "The hex form of " << input << " is: ";
    int decimal = input;
    cout << hex << uppercase << decimal << "\n";
    decimal = NULL;
    input = NULL;
    Sleep(3000);
}

And on the first run through it works. For example, if I enter 7331 I get:

The hex form of 7331 is 1CA3

But if I try it a second time (with the same input) I get:

The hex form of 1CA3 is 1CA3

I can try this with any integer input and it works fine for the first run through but after that it puts the base 16 number in twice.

  • It's not actually my code, I just wanted to show it was contained in a loop. Let me fix –  Jan 17 '18 at 01:07
  • 1
    Close-voter: what is unclear about this? I find the question to be very clear, OP has mentioned their inputs, outputs and what they expect. The example is more-or-less complete. – Tas Jan 17 '18 at 01:11
  • Some stream manipulators are [sticky](https://stackoverflow.com/questions/1532640/which-iomanip-manipulators-are-sticky), some are not. `std::hex` is _sticky_. – Ron Jan 17 '18 at 01:27
  • Avoid `using namespace std` – klutt Jan 17 '18 at 09:39

3 Answers3

3

You need to reset your stream. When you apply std::hex to std::cout, it applies permanently to the stream (std::cout), and you need to reset it. You can simply change your program to this:

cout << "The hex form of " << std::dec << input << " is: ";
Tas
  • 7,023
  • 3
  • 36
  • 51
0

your FIX:

cout << "The hex form of "<< dec << input << " is: ";
0

You could even shorten your code:

while (true)
{
    int input;

    cout << "Enter the base 10 number: ";
    cin >> input;
    cout << "The hex form of " << dec << input << " is: ";
    cout << hex << uppercase << input << "\n";

    Sleep(3000);
}
sky3
  • 43
  • 1
  • 6
  • Yeah, that's how I originally had it. I added the other stuff to try and 'clear' my variables. –  Jan 17 '18 at 01:36