gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:50:51 25 4
gpt4 key购买 nike

目前,当我打印变量的地址时, 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com