且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从C ++中的pgm文件读取数据

更新时间:2023-01-18 19:26:00

有很多不同的方法来解析文件。对于这种情况,您可以查看此网站上的答案。就我个人而言,我将使用getline()和test / parse每一行(存储在变量line)循环,你也可以使用stringstream,因为它更容易使用多个值:

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 :

第一行:测试P2(便携式灰色图)是否存在, / p>

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

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

第二行:不执行任何操作,可以继续下一个getline()

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

第三行:存储图像的大小;使用stringstream可以做到这一点

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

您可以尝试此代码,需求:

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();
}






/ strong>


EDIT

这里是一个好的教程如何使用stringstreams