【发布时间】:2016-11-10 17:39:36
【问题描述】:
假设您正在读取这样的 PPM 文件:
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();
}
有人删除了标题中的宽度或高度值。 现在 b 值将以字节形式读取一个 RGB 数字。是否存在 if 语句不会阻止程序结束的情况?换句话说,有没有一种优化的方法来防止此类错误?
【问题讨论】:
-
读取为一行(使用
getline),将字符串放入istringstream并使用字符串流解析值。应该稍微简化错误处理。 -
您还必须注意标题中可能包含的 cmets(以
#开头的行)。 -
是的,我知道。我会处理的。