用于从文本文件C ++中读取的标准循环

时间:2016-05-31 16:23:18

标签: c++ file error-handling eof

我正在学习如何在C ++中使用文件,作为初学者,我有一些疑问,我想澄清一下:

在我的书中,作者介绍了流状态,并编写了这段简单的代码来展示如何阅读,直到我们到达文件末尾或终止符:

// somewhere make ist throw if it goes bad : 
void fill_vector(istream& ist, vector<int>& v, char terminator)
{
    ist.exceptions(ist.exceptions() | ios_base::badbit); 

    for (int i; ist >> i;) v.push_back(i); 
    if (ist.eof()) return; // fine: we found end of file 

    // not good() not bad() and not eof(), it must be fail()
    ist.clear(); 

    char c; 
    ist >> c; // read a character, hopefully terminator

    if (c != terminator) {  // not the terminator, so we must fail
        ist.unget();        // maybe my caller can use that character 
        ist.clear(ios_base::failbit); 
    }
}

这是第一个例子,它提供了一种有用的方法来读取数据,但我在第二个例子中遇到了一些问题,作者说:

  

通常情况下,我们希望检查我们的阅读情况,这是一般策略,假设ist是一个&#39; istream&#39;:

for (My_type var; ist >> var;) { // read until end of file 
    // maybe check that var is valid 
    // do something with var

}

if (ist.fail()) {
    ist.clear(); 
    char ch; 
    // the error function is created into the book : 
    if (!(ist >> ch && ch == '|')) error("Bad termination of input\n"); 

}
// carry on : we found end of file or terminator
  

如果我们不想接受终结符 - 也就是说,只接受结束文件作为结束 - 我们只需在调用error()之前删除测试。

这是我的疑问:在第一个例子中,我们基本上检查了istream的每个可能状态,以确保读取按照我们想要的那样终止,并且那个&#39; s好。但我在理解第二个例子时遇到了问题:

  1. 作者在调用错误之前说要删除测试时的含义是什么?

    1. 读取时是否可以避免触发eof和fail?如果是,怎么样?
  2. 我真的很困惑,我无法理解这个例子,因为从我完成的测试中,故障排除将始终在eofbit之后设置,那么检查的意义是什么如果它始终被触发,则为failbit?为什么作者这样做

1 个答案:

答案 0 :(得分:1)

  

如果我在作者说的错误调用之前删除了测试,那么代码会发生什么?这不会没用,因为我只会检查流的不良状态吗?

我想我明白你的意思了。不,它并没有真正无用,因为你会告诉别人(我不知道error实际上做了什么),程序员(例外)或用户(标准输出),数据有一些无效数据,以及有人必须采取相应的行动。

它可能没用,但这取决于你希望函数做什么,例如,如果你希望它只是默默地忽略错误并使用已处理的正确数据,它真的无用。

  

如果我在不使用任何其他终结符的情况下到达该文件的末尾,我怎样才能从文件中读取数据?

我看不出你的意思,你已经在两个例子中都这样做了:

if (ist.eof()) return; // fine: we found end of file 

if (ist.fail()) { //If 'ist' didn't fail (reaching eof is not a failure), just skip 'if'