user6952065
user6952065

Reputation:

cout prints the incorrect value

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.

Upvotes: 1

Views: 655

Answers (3)

sky3
sky3

Reputation: 43

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);
}

Upvotes: 0

Tas
Tas

Reputation: 7111

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: ";

Upvotes: 3

mariusz_latarnik01
mariusz_latarnik01

Reputation: 659

your FIX:

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

Upvotes: 0

Related Questions