C ++中的文件结束 [英] End of File in C++

查看:321
本文介绍了C ++中的文件结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储在文本文件中的n X 2矩阵。我尝试在C ++中读取它

I have a n X 2 matrix stored in a text file as it is. I try to read it in C++

nb_try=0;
fin>>c_tmp>>gamma_tmp;
while (!fin.eof( ))      //if not at end of file, continue reading numbers
{
  // store
  cs_bit.push_back(c_tmp);
  gammas_bit.push_back(gamma_tmp);
  nb_try++;

  // read
  fin>>c_tmp;
  assert(!fin.fail( )); // fail at the nb_try=n   
  if(fin.eof( ))break;
  fin>>gamma_tmp; // get first number from the file (priming the input statement)
  assert(!fin.fail( ));    

}

第一个assert失败,即fin.fail true,当nb_try == n,当尝试读取不存在的第一个数字时发生。但是如何fin.eof()在读取最后一个数字后不是真的?它是否意味着它只有在读取第一个数字时,才存在?同样,fin.fail()和fin.eof()是否同时变为true?

The first assert failes, i.e. fin.fail( ) is true, when nb_try==n, which happens when it tries to read the first number which does not exist. But how come fin.eof( ) is not true after reading the last number? Does it mean it becomes true only when reading the first number that does ot exist? Also is it true that fin.fail( ) and fin.eof( ) are becoming true at the same time?

感谢和问候!

推荐答案

这是读取文件的错误方法:

This is the wrong way to read a file:

while (!fin.eof( ))
{
      // readLine;
      // Do Stuff
}

标准模式是:

while(getlineOrValues)
{
    // Do Stuff
}

所以仔细看看你的代码,我认为它会写成:

So looking at your code quickly I think it would be asier to write it as:

while(fin>>c_tmp>>gamma_tmp)
{
    // loop only eneterd if both c_tmp AND gamma_tmp
    // can be retrieved from the file.

    cs_bit.push_back(c_tmp);
    gammas_bit.push_back(gamma_tmp);
    nb_try++;   
}

问题是EOF只是真的 AFTER 你试着阅读过去。在文件中没有留下要读取的字符与EOF为真不相同。所以你读取最后一行并获取值,没有什么可以读取,但EOF仍然为false,所以代码重新进入循环。当它尝试并读取c_tmp时,EOF被触发,你的断言变成梨形。

The problem is that EOF is only true AFTER you try and read past it. Having no character left in the file to read is not the same as EOF being true. So you read the last line and get values and there is nothing left to read, but EOF is still false so the code re-enter the loop. When it tries and read the c_tmp then EOF gets triggered and your asserts go pear shaped.

解决方案是将读取作为while条件。读取的结果是流。但是当一个流在布尔上下文(如while条件)中使用时,它被转换为类型,可以像bool一样使用(技术上它是一个void *,但这不重要)。

The solution is to put the read as the while condition. The result of doing the read is the stream. But when a stream is used in a boolean context (such as a while condition) it is converted into a type that can be used as like a bool (Technically it is a void* but thats not important).

这篇关于C ++中的文件结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆