Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a C++ way to format addresses and pointers with iostream?

Tags:

c++

iostream

I have something like

unsigned x = 16;
unsigned* p = &x;

std::cout << std::hex << std::setw(16) << std::setfill('0') << x << std::endl;
std::cout << std::hex << std::setw(16) << std::setfill('0') << p << std::endl;

output:

0000000000000010
000x7fffc35ba784

ostream::operator<< is overloaded for this? I can write this correctly with C, but I was wondering if there is a proper way to do this with iostream.

like image 542
Albert Myers Avatar asked Sep 12 '13 22:09

Albert Myers


1 Answers

Use internal like this:

#include <iostream>
#include <iomanip>

int main()
{
    unsigned x = 16;
    unsigned* p = &x;

    std::cout << std::hex << std::setw(16) << std::setfill('0') << x << std::endl;
    std::cout << std::hex << std::setw(16) << std::setfill('0') << p << std::endl;
    std::cout << std::internal << std::hex << std::setw(16) << std::setfill('0') << p << std::endl;
}

This gives:

0000000000000010
000x7fffd123c1a4
0x007fffd123c1a4
like image 180
Mats Petersson Avatar answered Sep 28 '22 16:09

Mats Petersson