困惑如何确保数据在IOStream中"Good"

Confused How to Make Sure Data is "Good" in IOStream

本文关键字:数据 IOStream Good 确保 何确保      更新时间:2023-10-16

我很确定我在类中错误地编写了两个函数的代码。我很困惑如何正确地接收两段数据(x和y)并确保它们处于良好状态。

/**
 * Requires: ins is in good state.
 * Modifies: ins, x, y.
 * Effects:  Reads point in form (x,y).
 */
void read(istream& ins);
/**
 * Requires: outs is in good state.
 * Modifies: outs.
 * Effects:  Writes point in form (x,y).
 */
void write(ostream& outs);

void Point::read(istream& ins) {
char junk;
char junk2;
char junk3;
while (cin.good()) {
    cin >> junk >> x >> junk2 >> y >> junk3;
}
}
void Point::write(ostream& outs) {
while (cout.good()) {
    cout << "(" << x << "," << y << ")";
}
}

您可以在读取后使用istream的.bad()函数来确定是否存在问题。"问题可能是i/o操作上的逻辑错误" (failbit)或" i/o操作上的读写错误" (badbit)。

下面,我将cin替换为ins,因为您已经将其作为参数传递,并且它显然意味着您需要从中提取的istream对象。我还添加了局部变量(使用下划线作为前缀),然后只复制到xy,如果没有错误。

如果检测到错误,您可以简单地"返回",但是不会向您的用户表明发生了读取错误并且x/y没有被触摸。作为一种替代方法,我选择抛出一个异常,但是您也可以选择cout/cerr消息,然后返回,或者选择返回结果(成功/失败),而不是使用void返回并让调用函数处理错误。

void Point::read(istream& ins) {
  char _junk;
  int _x, _y;
  ins >> _junk >> _x >> _junk >> _y >> _junk;
  if (ins.bad()) 
    throw "Error";
  x = _x;  // Assuming x and y are members of class Point
  y = _y;
}

对于Point::write函数,不要使用while循环。通常我不检查ostream对象,但是如果你真的想检查,那么在你写之前和之后检查.good()是否为真。如果你检测到一个问题,你可以随心所欲地处理这个错误;return, throw异常,并/或记录错误