c++ - 如何在 C++ 中以大写形式打印地址(十六进制值)

标签 c++

我正在尝试以十六进制打印变量的地址(引用),也以大写字母打印。但是我看到我能够以大写形式打印相当于 77 的十六进制值,但不能打印变量的地址(引用)。有人可以帮帮我吗?

以下是我遇到困难的程序。

#include <iostream>
#include <string>

using namespace std;


void print_nb_of_items(const int nb_of_apple, const int& nb_of_pens)
{
    cout << "Number of apples = " << nb_of_apple << endl;
    cout << "Number of pens = " << nb_of_pens << " Address = " << uppercase << hex << &nb_of_pens << endl;
    cout << "Hex output in uppercase = " << uppercase << hex << 77 << endl;
}

/* The main function */

int main(int argc, char * argv[])
{
    int nb_apple = 24;
    int nb_pens = 65;
    print_nb_of_items(nb_apple, nb_pens);

    return 0;
}

我得到的程序的输出是:

Number of apples = 24
Number of pens = 65 Address = 0xbffbd438
Hex output in uppercase = 4D

我希望地址打印为:0xBFFBD438。 我该怎么做?

最佳答案

"I want the address to be printed as: 0xBFFBD438. How do I do that?"

嗯,@MatsPetterson在他的头上击中了钉子comment ,将地址值转换为 uintptr_t

cout << "Number of pens = " << nb_of_pens 
     << " Address = 0x" << uppercase << hex 
     << uintptr_t(&nb_of_pens) << endl;
     // ^^^^^^^^^^           ^

让它正常工作(请参阅完整工作示例 here)。


更深入的解释:
实现

 std::ostream operator<<(ostream& os, void* ptr);

未由标准进一步指定,并且可能根本不受 std::uppercase I/O 操纵器的影响/考虑。将指针值转换为普通数字,将使 std::uppercasestd::hex I/O 操纵器生效。

关于c++ - 如何在 C++ 中以大写形式打印地址(十六进制值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28795137/

相关文章:

c++ - 是否可以使用 boost 构建并发进程间消息队列?

c++ - 哈希表创建

c++ - 如何处理来自核心准则检查器的有关gsl::at的静态分析警告?

C++ 自定义字符串修剪实现 valgrind 警告

C++ 设置 "flags"

c++ - 带有 Unicode UTF-16 (1200) 代码页字符串表的 VerQueryValue 失败

c++ - 重用基类中的模板变量

c++ - 加载共享库时出错

c++ - 单独运行的不同执行时间

c++ - Visual Studio 中的 std::begin 和 std::end 迭代器