reversing a vector

Jan 30, 2012 at 10:23pm
The point of this lab is to read in a pgm file and horizontally flip it. I can't figure out why what i have wont flip every row. it works for some of the smaller programs that are like 12 by 13. but when it gets up to 300 by 240, it fails.

#include <iostream>
#include <vector>
#include <cstdlib>
#include <stdio.h>
using namespace std;

int main()
{
int row, j, i, counter2 = 0, column,counter = 0, num, num255;
string P2;
vector <int> allNums, reverse;

cin >> P2; // reads in the name
if(P2!= "P2"){
exit(0);
}
cin >> row; // reads the row
if (row < 1){
exit(0);
}
cin >> column; // reads the column
if(column < 1){
exit(0);
}
cin >> num255; // makes sure it has the 255 number
if(num255 != 255){
exit(0);
}
cout << P2 << endl;
cout << row << " " << column << endl;
cout << num255 << endl;
while (cin >> num){ // troublesome area.
if(num < 0)
exit(0);
allNums.push_back(num); // reads all the pixels into a vector
if (counter == column -1) // every time it reaches the end of the columns, it should print out backwards the row.
{
while (counter >=0)
{
cout << allNums[counter] << endl;
counter--;
}
counter = 0;
allNums.clear();
}
else
counter++;
}
}
Jan 30, 2012 at 11:42pm
Notes:
- Why are you using exit() instead of return, and why are you returning 0 instead of 1 (or some other non-zero value to indicate that the program failed)?
- Modern PGM images may have a 'num255' value other than 255. As it is, it doesn't actually matter, in any case, as you are not manipulating the pixel values, just their ordering.
- You have a lot of unused variables there...
- You should check if (counter == row -1), mind you. You have the names backwards: the first number is the number of columns, the second is the number of rows.

As per your question:
- I don't see why it should be failing. (I haven't bothered to properly format your code, though...)
- Does your test PGM have comments in it? (Your program will choke if it does.)
- Inside your inner loop, you cout an endl, when you should be printing a space or something. Print a newline and flush only after printing the entire line.

Hope this helps.

Edited because I forgot something
Last edited on Jan 30, 2012 at 11:43pm
Jan 31, 2012 at 12:08am
yeah, switching the rows and columns did it. thank you so much!
and sorry about the messiness of the code and all, i was trying out different stuff and just posted what had seemed to work the best. i hadn't really cleaned it up yet.
Topic archived. No new replies allowed.