困惑如何确保数据在IOStream中"Good"
Confused How to Make Sure Data is "Good" in IOStream
我很确定我在类中错误地编写了两个函数的代码。我很困惑如何正确地接收两段数据(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
对象。我还添加了局部变量(使用下划线作为前缀),然后只复制到x
和y
,如果没有错误。
如果检测到错误,您可以简单地"返回",但是不会向您的用户表明发生了读取错误并且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
异常,并/或记录错误
相关文章:
- 防止主数据类型C++的隐式转换
- 用于访问容器<T>数据成员的正确 API
- 嵌套在类中时无法设置成员数据
- 使用流处理接收到的数据
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 在cuda线程之间共享大量常量数据
- C++将文本文件中的数据读取到结构数组中
- 如何在C++中序列化结构数据
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 在c代码之间共享数据的最佳方式
- 链表,反向函数,数据结构
- 数据成员SFINAE的C++17测试:gcc vs clang
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 如何对点云数据进行排序
- 如何避免与"asio::ip::tcp::iostream"的数据竞争?
- 在iostream报头中使用静态数据
- 困惑如何确保数据在IOStream中"Good"
- 如何使用 gnuplot-iostream.h 读取C++中的数据文件