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

标签 c++ matrix cin ppm

我正在尝试使用以下代码从标准输入读取 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 参数之后都有一个空格字符:

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).
...

在您的代码中,这个额外的空格不会从流中提取出来,因为 read() 从当前位置开始读取。当您读取固定数量的字符时,这个额外的空间会导致您的代码忽略最后一个字符。

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

关于c++ - 在 C++ 中读取 PPM 图像缺少最后一个像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35462990/

相关文章:

c++ - 如何在 C++11 中存储任意方法指针?

python - 用递增序列填充连续的零序列

r - 从类 "simple_triplet_matrix"转换为类 "matrix"

c++ - 如何使用 program.exe < text.txt 使用 C++ 读取输入

c++ - 当我不需要 C++ 计算时如何忽略某些输入?

多个子级之间的 C++ 管道

c++ - std::vector 大小?

c++ - fstream 不会打印到文件

python - 创建非冗余相关矩阵Python最有效的方法?

c++ - cin.get() 循环