2

I've to print on the standard output some std::uint16_t values as hexadecimal with the following text formatting: 0x##. I found this code online which works fine for every value except 0:

std::cout << std::internal 
          << std::setfill( '0' ) 
          << std::hex 
          << std::showbase 
          << std::setw( 4 ) 
          << value << std::endl;

For some reason I don't understand, 0 is printed as 0000. All the other values are correctly printed as expected.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
nyarlathotep108
  • 5,275
  • 2
  • 26
  • 64
  • 5
    As seen in the [Notes section here](http://en.cppreference.com/w/cpp/io/manip/showbase#Notes), this was a deliberate choice. How to get around it? Not sure, I'm afraid, never needed to. Sounds like you might need to get into creating your own [`num_put`](http://en.cppreference.com/w/cpp/locale/num_put), which is a pain in the proverbials. – BoBTFish Mar 10 '16 at 15:45
  • _One question per question please._ – Lightness Races in Orbit Mar 10 '16 at 15:59
  • 3
    I'm fairly sure a programmer designed this system ("Zero is the same in every base, what's the problem?"). I think `... << "0x" << setw(2) << ...` should work. – molbdnilo Mar 10 '16 at 16:12

1 Answers1

1

For your additional question. You only need to set the width again. The rest of the manipulators are persistent.

std::cout << std::internal 
      << std::setfill( '0' ) 
      << std::hex 
      << std::showbase ;

for(std::uint16_t i =1;i<255;++i){
      std::cout<< std::setw( 4 )<<i<<"\n";
}

To overcome the setw issue here are some workarounds: “Permanent” std::setw

Community
  • 1
  • 1
MagunRa
  • 543
  • 4
  • 13