Search code examples
c++file-ioioppm

Reading bytes from a P6 PPM file into a character array (C++)


Here is the relevant code:

string s;
int width, height, max;

// read header
ifstream infile( "file.ppm" );  // open input file
infile >> s; // store "P6"
infile >> width >> height >> max; // store width and height of image
infile.get(); // ignore garbage before bytes start

// read RGBs
int size = width*height*3;
char * temp = new char[size]; // create the array for the byte values to go into
infile.read(temp, size); // fill the array

// print for debugging
int i = 0;
while (i < size) {
    cout << "i is " << i << "; value is " << temp[i] << endl;
    i++;
}

Then, the output that I get says that the values in the array are either blank, or "?". I guess this means the bytes were not converted into chars properly?

i is 0; value is

i is 1; value is

i is 2; value is

i is 3; value is ?

i is 4; value is ?

...etc.


Solution

  • It looks like you want it to print a BYTE value, not a character. Try this:

    cout << "i is " << i << "; value is " << (int)(temp[i]) << endl;
    

    By casting the char to an int, cout will print the value, not the ASCII code.