ファイルを解析する方法はたくさんあります。このようなものについては、このサイトの回答を見ることができます。個人的には、getline()のループを使用して、すべての行(変数「line」に格納されている)をテスト/解析します。複数の値で使用する方が簡単なので、文字列ストリームを使用することもできます。
アイディア
最初の行: P2(ポータブルグレーマップ)が存在することをテストします。
if(line.compare("P2")) ...
2行目:何もしないで、次のgetline()に進むことができます
3行目:画像のサイズを保存します。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();
}
編集
これは、文字列ストリームの使用方法に関する優れたチュートリアルです。