cout 打印不正确的值

cout prints the incorrect value

所以,我正在尝试制作一个基本的 C++ 程序来转换 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);
}

并且在第一个 运行 通过它时有效。例如,如果我输入 7331,我会得到:

The hex form of 7331 is 1CA3

但是如果我第二次尝试(使用相同的输入)我得到:

The hex form of 1CA3 is 1CA3

我可以用任何整数输入来尝试这个,它在第一个 运行 时工作正常,但之后它将以 16 为基数的数字输入两次。

你的修复:

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

您需要重置直播。当您将 std::hex 应用于 std::cout 时,它会永久应用于流 (std::cout),并且您需要重置它。您只需将程序更改为:

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

您甚至可以缩短代码:

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