我正在尝试以十六进制打印变量的地址(引用),也以大写字母打印。但是我看到我能够以大写形式打印相当于 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::uppercase
和 std::hex
I/O 操纵器生效。
关于c++ - 如何在 C++ 中以大写形式打印地址(十六进制值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28795137/