问题描述
到目前为止,我可以读取每一行并打印到控制台:
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;
}
}
然而,pgm文件显然总是有在数据之前开始:
However a pgm file apparently will always have the following at the start before the data:
P2
# test.pgm
24 7
15
如何调整我的代码,使其检查P2是否存在,忽略任何注释#),并存储变量和随后的像素数据?
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?
我对c ++有点失落和新奇,所以任何帮助都是惊喜。
I'm a bit lost and new to c++ so any help is appreicated.
>
推荐答案
有很多不同的方法来解析文件。对于这种情况,您可以查看上的答案。就我个人而言,我将使用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
这里是一个。
这篇关于如何从C ++中的pgm文件读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!