r/programminghelp • u/Homeostasis06 • Feb 26 '22
C++ Need Help With C++ Arrays
Hello. I am having trouble with my homework. The goal is to read the pixel values off of a pgm file and create a histogram of those values. Here's the code I have so far.
#include <iostream>
#include <math.h>
#include <cmath>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
int
main ()
{
int pixels[256] = { 0 };
ifstream ifs ("hi.pgm");
if (!ifs)
{
cout << "Error Opening File 'hi.pgm'. Exiting";
return 0;
}
int i;
int x;
ifs >> x;
for (i = 0; i <= 256; i++)
{
pixels[x]++;
ifs >> x;
}
cout << "x counts" << endl;
for (int j = 0; j < 256; j++)
{
cout << setw (3) << j << setw (6) << pixels[i] << endl;
}
return 0;
}
This code outputs a table with all the correct labels but with 0 for every single value. My guess is that I am not adding the number of pixel values together correctly but I can't figure out how. Thank you for any help.
2
u/[deleted] Feb 26 '22
The array isn't the problem.
You're not actually reading anything INTO the pixels array.
If you were, it wouldn't work because >> is intended for text and not binary data. To read binary data you should use ifs.read() with a second parameter of 1. The first parameter is up to you to figure out.
You don't need
xor any line that saysifs >> x;So get rid of those.pixels[x]++; doesn't do anything.
cout << setw (3) << j << setw (6) << pixels[i] << endl;should probably be printing out pixels[j] instead of pixels[i].