到目前为止,我可以读取每一行并将其打印到控制台:
void readFile(){
string line;
ifstream myfile("example1.pgm");
if (myfile.is_open()){
while (myfile.good()){
getline (myfile,line);
cout << line;
}
}
然而,pgm 文件显然总是在数据之前的开头包含以下内容:
P2
# test.pgm
24 7
15
我如何调整我的代码,以便它检查“P2”是否存在,忽略任何注释(#),并存储变量和后续像素数据?
我对 C++ 有点迷茫,所以非常感谢您的帮助。
Thanks
有很多不同的方法来解析文件。对于这样的事情,你可以看看答案这个网站。就我个人而言,我会使用 getline() 循环并测试/解析每一行(存储在变量“line”中),您也可以使用字符串流,因为它更容易使用多个值:
Idea
第一行 :测试 P2(便携式灰度图)是否存在,也许使用类似的东西
if(line.compare("P2")) ...
第二行 :什么也不做,你可以继续下一个 getline()
第三行:存储图像的大小;使用 stringstream 你可以这样做
int w,h;
ss >> w >> h;
以下几行:存储像素数据直到到达文件末尾
结果代码
您可以尝试此代码并根据您的需要进行调整:
#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
这里有一个关于如何使用 stringstreams 的好教程.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)