gpt4 book ai didi

c++ - 在 C++ 中打印十六进制值到控制台

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:00:10 30 4
gpt4 key购买 nike

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
char array[10];

for(int i = 0; i<10;i++)
{
array[i] = 'a' + i;
}

char* test = array;

printf("%x\n", test);
cout << hex << test << endl;

}

这个的输出是:

bffff94e
abcdefghijN???

为什么打印的不是同样的东西?

最佳答案

cout << hex << test << endl; 

它打印字符串,而不是地址。这是因为 operator<< 重载了这需要 char const*作为参数,此重载将参数视为字符串。

如果要打印地址,请将参数转换为 void*所以operator<<其他重载将被调用,它将打印地址。

cout << hex << static_cast<void*>(test) << endl;

将以十六进制格式打印地址。

请注意 hex这里不需要流操纵器,因为地址将以十六进制格式打印。所以

cout << static_cast<void*>(test) << endl;

足够了。

关于c++ - 在 C++ 中打印十六进制值到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11095653/

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