从 P6 PPM 文件读取字节到字符数组 (C++)

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

相关代码如下:

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++;
}

然后,我得到的输出显示数组中的值要么为空,要么为“?”。我想这意味着字节没有正确转换为字符?

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 ?

...等

您似乎希望它打印 BYTE 值,而不是字符。试试这个:

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

通过将 char 转换为 int,cout 将打印值,而不是 ASCII 代码。