How to read hex values from a file using fstream in c++?

ardiyu07 picture ardiyu07 · Feb 18, 2011 · Viewed 37.8k times · Source

As the title says, how do you read hex values using fstream?

i have this code: (let's say we have "FF" in the file.)

fstream infile;
infile.open(filename, fstream::in|fstream::out|fstream::app);

int a;
infile >> std::hex;
infile >> a;
cout << hex << a;

but this does not give me any output instead of ff. I know there is a fscanf(fp, "%x", val) but I am curious is there any way to do this using stream library.

UPDATE:

My code was right all along, it turns out my error was I couldn't read "FFF" and put it in variable a,b,c like this

while (infile >> hex >> a >> b >> c)
  {
    cout << hex << a << b << c << "\n";
  }

Can somebody help me with this? do I have to separate every HEX values i want to read with space? because infile >> hex >> setw(1) doesn't work..

Answer

Bernd Elkemann picture Bernd Elkemann · Feb 18, 2011

You can use the hex modifier

int n;
cin >> hex >> n;