Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read in data from a pgm file in C++

Tags:

c++

parsing

pgm

So far I can read every line and print it out to the console:

void readFile(){

   string line;
   ifstream myfile("example1.pgm");

   if (myfile.is_open()){
       while (myfile.good()){
         getline (myfile,line);
         cout << line;
       }
   }

However a pgm file apparently will always have the following at the start before the data:

P2
# test.pgm
24 7
15

How can i adapt my code so that it checks that "P2" is present, ignores any comments (#), and stores the variables and subsequent pixel data?

I'm a bit lost and new to c++ so any help is appreicated.

Thanks

like image 489
ostegg548 Avatar asked Dec 21 '22 06:12

ostegg548


1 Answers

There are a lot of different ways to parse a file. For something like this, you could look at the answers on this site. Personally, I would go with a loop of getline() and test/parse every line (stored in the variable "line"), you can also use a stringstream since it is easier to use with multiple values :

Idea

First line : test that P2 (Portable graymap) is present, maybe with something like

if(line.compare("P2")) ...

Second line : do nothing, you can go on with the next getline()

Third line : store the size of the image; with a stringstream you could do this

int w,h;
ss >> w >> h;

Following lines : store the pixel data until you reach the end of the file

Resulting code

You can try this code and adapt it to your needs :

#include <iostream> // cout, cerr
#include <fstream> // ifstream
#include <sstream> // stringstream
using namespace std;

int main() {
  int row = 0, col = 0, numrows = 0, numcols = 0;
  ifstream infile("file.pgm");
  stringstream ss;
  string inputLine = "";

  // First line : version
  getline(infile,inputLine);
  if(inputLine.compare("P2") != 0) cerr << "Version error" << endl;
  else cout << "Version : " << inputLine << endl;

  // Second line : comment
  getline(infile,inputLine);
  cout << "Comment : " << inputLine << endl;

  // Continue with a stringstream
  ss << infile.rdbuf();
  // Third line : size
  ss >> numcols >> numrows;
  cout << numcols << " columns and " << numrows << " rows" << endl;

  int array[numrows][numcols];

  // Following lines : data
  for(row = 0; row < numrows; ++row)
    for (col = 0; col < numcols; ++col) ss >> array[row][col];

  // Now print the array to see the result
  for(row = 0; row < numrows; ++row) {
    for(col = 0; col < numcols; ++col) {
      cout << array[row][col] << " ";
    }
    cout << endl;
  }
  infile.close();
}

EDIT

Here is a good tutorial on how to use stringstreams.

like image 89
BenC Avatar answered Dec 24 '22 02:12

BenC