0

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.

user
  • 352
  • 3
  • 13
  • ASCII encoding does not assign a printable character to all values between 0 and 255. – IInspectable Feb 17 '16 at 22:57
  • _"... bytes were not converted into chars ..."_ What do you mean? – πάντα ῥεῖ Feb 17 '16 at 22:57
  • @πάνταῥεῖ I don't know... i'm really confused. I want the bytes to be represented as chars between 0 and 255 in the array. – user Feb 17 '16 at 23:09
  • 1
    @user So you want to see the numbers? The duplicate question well serves you with the answer you need. – πάντα ῥεῖ Feb 17 '16 at 23:11
  • Important remark : you have to open the file in `ios::binary` mode to safely read binary data. If you don't, on windows platforms, the binary sequence 13 10 would be read 10 due to the CR LF to LF conversion, causing color components to be lost. – Christophe Feb 17 '16 at 23:26

1 Answers1

1

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.

Kyle A
  • 928
  • 7
  • 17
  • So I did this and now the values printed are either 0, -128, or -1, which is definitely not what they're supposed to be. – user Feb 17 '16 at 23:04
  • 3
    @user: That should be `unsigned(temp[i])` instead of `(int)(temp[i])`. – IInspectable Feb 17 '16 at 23:05
  • @IInspectable now the values are all either 0 or 4294967168.... – user Feb 17 '16 at 23:07
  • 1
    @user: Your array needs to be of type `unsigned char[size]` as well. – IInspectable Feb 17 '16 at 23:10
  • @IInspectable I will change the initialization to "unsigned char temp[size];". Don't I have to change this line as well? "infile.read((char*)&temp, size*sizeof(temp[0])); // coercion" since it is no longer an array of char *, but just char? – user Feb 17 '16 at 23:15