I am attempting to read a PPM image from standard input with this code:
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;
}
}
However, when I output the PPM image unchanged, I am missing the very last pixel. Everything else seems to work perfectly. Any ideas?
The PPM file format has for all its variant a single space character following the colourMax
parameter:
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).
...
In your code, this extra whitespace is not extractacted from the stream because read()
starts reading at the current position. And as you read an fixed number of chars, this extras space, causes your code to ignore the last char.
Solution: just cin.ignore();
before starting your reading loops.