目前,当我打印变量的地址时,
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++) 编译器编译后的打印方式。
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/