1

The assignment is to manipulate a PPM file and to store the RGB values to an array. I am able to grab the header of the file and get P6, the width, the height, and the maximum RGB value but I cannot get the RGB values themselves. I know that pixel data is separated by a white space but stream input still cannot find it. We have not learned classes or pointers yet so can it be done without using either?

#include <fstream>
#include <iostream>
#include <string>

const int WID = 648;
const int HEIGHT = 486;

int main() {
  int arr[HEIGHT * WID * 3];
  unsigned char r, g, b;

  std::string header;
  int wid, hei, max;
  std::ifstream fin;

  fin.open("file.ppm");
  if (fin.fail()) {
    std::cout << "file did not open: << std::endl;
  }

  fin >> header;
  fin >> wid >> hei >> max;

  for (int i; i < HEI * WID * 3; ++i) {
    r = arr[i];
    g = arr[i + 1];
    b = arr[i + 2];
  }

  std::cout << header << wid << hei << max << r << g << b;

  fin.close();

  return 0;
}

This code will display the P6, wid, hei, and max but not RGB pixels. If I change the types around on unsigned r g b than I can get a 0 or a symbol. If use a string to capture everything after max I get a ton of random symbols. Help would be greatly appreciated I've been stuck for a while. Any help will be appreciated.

Jacks
  • 803
  • 1
  • 6
  • 16
benjawmin
  • 13
  • 5
  • 1
    Strange -- If the file fails to open, your program goes ahead as if nothing is wrong. – PaulMcKenzie Dec 05 '19 at 21:00
  • `int arr[HEIGHT * WID * 3];` -- Assuming `sizeof(int) == 4` that is over 3.5 megabytes of stack memory. The stack is limited in size. Use heap memory, or make that array global. – PaulMcKenzie Dec 05 '19 at 21:05
  • 2
    Where do the values in `arr` come from?? – J. Doe Dec 05 '19 at 21:09
  • Please note that `r`, `g` and `b` are declared as `unsigned char`, so that, depending on their actual values, they may not be printable. Try `std::cout << ...<< (unsigned)r << ...<< '\n';` instead, but first you should also *read* those values. – Bob__ Dec 05 '19 at 21:10
  • If the header is P6 the data are binary, so you must open with `ios::binary` flag. You should then get the width and height and multiply them together. Then multiply that by 2 if MAX_VAL exceeds 255. Then `new()` that much space. Then use `fin.read()` to load the pixels. – Mark Setchell Dec 05 '19 at 21:23
  • 1
    `for (int i;` ... sigh. Undefined behavior. Pretty much every second or third line of the shown program has a problem. What you need [is a good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). You will get far more benefit from focusing on some C++ fundamentals and basic concepts, and getting them solid, before attempting to tackle something like parsing a graphics file. – Sam Varshavchik Dec 05 '19 at 21:26
  • @MarkSetchell *Then new() that much space.* – `new` in user code?? `std::vector` ftw. – J. Doe Dec 06 '19 at 16:46

0 Answers0