Reputation: 9093
I am trying read the header for a PGM file, which I found could have the follow variations:
P2
255 255
255
or
P2
255 255 255
or
P2 255 255 255
right now, I got this code:
std::ifstream file(file_name);
std::string line_one, line_two, line_three, line_pixels;
char magicNumber;
int width, height;
while(getline(file, line_one)) {
if(line_one.size() > 0 && line_one.at(0) != '#') {
magicNumber = line_one.at(1);
break;
}
}
while(getline(file, line_two)) {
if(line_two.size() > 0 && line_two.at(0) != '#') {
std::stringstream ss(line_two);
ss >> width >> height;
break;
}
}
while(getline(file, line_three)) {
if(line_three.size() > 0 && line_three.at(0) != '#') {
this->max_value = stoi(line_three);
break;
}
}
which works fine for the first variation, but not so much for the other two. I think this could be solve by checking if the end of line was reached after each 'while'/ 'getline'
blocks above. Am i right? If so, how to do that?
UPDATE
I try this code, but it is not skipping the lines with comments (starting with #):
std::ifstream file(file_name);
std::string line_one, line_two, line_three, line_pixels;
std::string magicNumber;
int width, height;
file >> magicNumber;
if(file.peek() == '#') {
std::string comment;
getline(file, comment);
}
file >> width;
if(file.peek() == '#') {
std::string comment;
getline(file, comment);
}
file >> height;
if(file.peek() == '#') {
std::string comment;
getline(file, comment);
}
file >> this->max_value;
if(file.peek() == '#') {
std::string comment;
getline(file, comment);
}
Upvotes: 0
Views: 38