在 C++ 中读取 PPM 图像缺少最后一个像素

Reading PPM image in C++ missing last pixel

我正在尝试使用以下代码从标准输入读取 PPM 图像:

cin >> format;
cin >> ppm->width >> ppm->height >> ppm->colourMax;

for (int r = 0; r < ppm->height; r++) {
  ppm->pixels[r] = new Pixel[ppm->width];
  for (int c = 0; c < ppm->width; c++) {
    Pixel p = Pixel();
    cin.read(reinterpret_cast<char *>(&p.r), sizeof(unsigned char));
    cin.read(reinterpret_cast<char *>(&p.g), sizeof(unsigned char));
    cin.read(reinterpret_cast<char *>(&p.b), sizeof(unsigned char));
    ppm->pixels[r][c] = p;
  }
}

但是,当我输出未更改的 PPM 图像时,我丢失了最后一个像素。其他一切似乎都很完美。有什么想法吗?

PPM file format 的所有变体在 colourMax 参数后都有一个 space 字符:

Each PPM image consists of the following:

...
5. A height, again in ASCII decimal.
6. Whitespace.
7. The maximum color value (Maxval), again in ASCII decimal. Must be less than 65536 and more than zero.
8. A single whitespace character (usually a newline).
...

在您的代码中,这个额外的白色space 没有从流中提取出来,因为read() 从当前位置开始读取。当您读取固定数量的字符时,这个附加值 space 会导致您的代码忽略最后一个字符。

解决方案:只是 cin.ignore(); 在开始阅读循环之前。