c++ - 使用 0x 表示法打印地址

标签 c++

目前,当我打印变量的地址时, cout << &a ,它显示为一个简单的十六进制数字,比方说:008FFBB8。

如何打印带有 0x 符号的地址?例如0x6FFDF4。

我尝试这样做:

cout << hex << &a;

但似乎不起作用。

最佳答案

有很多不同的解决方案,我想到的前两个是:

#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>

int main()
{

  std::cout << std::hex
            << "showbase: " << std::showbase<< 42 << '\n'
            << "noshowbase: " << std::noshowbase << 42 << '\n';


  //2nd solution
  std::string a{"008FFBB8"};
  std::cout << "Given: " << a << '\n';
  a.erase(0,2);
  a = "0x"+a;
  std::cout << "Edited: "<< a <<'\n';


  //3rd string to int so you can use standard arithmetics
  int b = std::stoul(a, nullptr, 16);
  std::cout << "Represented as int: " << b << '\n';



  std::cin.get();
}

编辑:

这是使用 GNU GCC(g++) 编译器编译后的打印方式。 enter image description here

Visual Studio 未按屏幕截图所示打印它的原因是 Visual Studio 倾向于不使用 GNU GCC,而是使用其 Microsoft 编译器 MSVC。 (There are other things MSVC isn't doing as you may expect btw.)但好消息:you can make it!here :)

这就是十六进制在您的配置中通过“MSVC”呈现的方式 我希望能回答您的问题,否则请发表评论:)

关于c++ - 使用 0x 表示法打印地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66802137/

相关文章:

c++ - C++中多线程的困惑

c++ - 无法使用复制初始化(即=)来构造带有初始化列表的类

c++ - 二进制 char 数组到 stringstream 并从缓冲区弹出

c++ - 如何使用 Visual Studio 在 dll 导出类中使用唯一指针 vector

c++ - 带有外部静态表的 constexpr 函数

c++ - 我们还应该优化 "in the small"吗?

c++ - clang tidy pro 类型成员 init resharper

c++ - 捕获音频输出

c++ - 使用 "extern"关键字而没有 #include "file.h"

c++ - 在C++中生成随机非重复数数组