Search code examples
c++hexoctal

How do I make the system print 0x before the hex number & 0 before the octal number?


My teacher says that for the assignment we are not allowed to manually print the 0x before the hex number, we have to make the system do it.

Currently my code looks like this:

cout << "Hex" << setw(12) << hex << static_cast<int>(letter) << setw(12) << hex
        << number << setw(12) << hex << static_cast<int> (symbol) << endl;

It prints the correct hex value but without the 0x.

Additionally, for octal numbers, I have to again, make the system print a 0 before the number (not manually. My code prints correct values, but without the preceding 0:

cout << "Octal" << setw(12) << setbase(8) << static_cast<int>(letter) << setw(12) << setbase(8)
    << number << setw(12) << setbase(8) << static_cast<int>(symbol) << endl;

Solution

  • Use std::showbase:

    std::cout << std::hex << std::showbase << 1234567890;