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

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

本文关键字:数组 字符 C++ 读取 字节 P6 PPM 文件      更新时间:2023-10-16

以下是相关代码:

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 为 0;值为

i 是 1;值是

i 是 2;值是

i 是 3;值是 ?

i 是 4;值是 ?

。等。

看起来您希望它打印 BYTE 值,而不是字符。试试这个:

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

通过将字符转换为整数,cout 将打印值,而不是 ASCII 代码。