Return Keyboard Hex Value

fattumsdad used Ask the Experts™
The following code (provided by bcladd on my last question) will return the value of any key pressed.  How do I get the program to return the hexadecimal value when a key is pressed instead (0x00 etc)?  As always, I appreciate any and all help.  Too bad they didn't award point for ASKING questions...  I'd be in the lead :-)

#include <conio.h>
using namespace std;

int main()
  char ch;
  while (ch = getch()) {

    cout << (int)ch << endl;
    if (ch == 'X') break;
  return 0;

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

How about

#include <iomanip>

and change the cout to

cout << hex << (int)ch << endl;


Or, if you want the 0x:

cout << "0x" << hex << (int)ch << endl;

Last followup to my own stuff, I promise:

    cout << "0x" << setfill('0') << setw(2) << hex << (int)ch << endl;

Prints the leading zero for numbers less than 0x10


Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial