Assuming you're reading a PPM file like this:
ifstream img;
img.open("Image.ppm", ios::binary);
try
{
if (img.fail())
{
throw("Can't open input file");
}
string header;
int w, h, b;
img >> header;
cout << header << endl;
if (header.compare("P6") != 0)
{
throw("Wrong format file. File needs to be P6 type!");
}
img >> w >> h >> b;
cout << w << " " << h << " " << b << endl;
if (b < 0 || b > 255)
{
throw("An error message");
}
img.ignore(256, '\n');
}
catch (const char *err)
{
fprintf(stderr, "%s\n", err);
img.close();
}
And someone removed the width or height value in the header. Now b value will read an RGB number in byte form. Is there any possible case that the if-statement won't prevent the program from ending? In other words is there an optimized method to prevent such errors?
getline
), put string into anistringstream
and use the string stream to parse the values. Should simplify error handling a little. – Some programmer dude#
) included in the header too. – J. Piquard