zoukankan      html  css  js  c++  java
  • c++中ifstream读文件的问题(关于eof())

      今天帮别人找BUG,是一段关于c++读写文件的问题,使用的是ifstream与outstream类,关于ofstream与ifstream的用法,此处不再獒述,见代码:

    #include<iostream>
    #include<fstream>
    using namespace std;
    
     int main()
     {
         ofstream outfile("student.dat");
         char name[8],id[8];
         int math,eng,computer;
    
         for(int  i = 0; i < 3; ++i)
         {
    
             cout<<" input name:  "; cin>>name;
             cout<<" input id:  "; cin>>id;
             cout<<" input math:  "; cin>>math;
             cout<<" input eng:  ";cin>>eng;
             cout<<" input computer:  "; cin>>computer;
            //写文件
             outfile<<name<<" "<<id<<" "<<math<<" "<<eng<<" "<<computer<<endl;
             
         }
    
       向文件写完之后,再从文件中读取,源码如下:
    include<iostream>
    #include<fstream>
    using namespace std;
    
     int main()
     {
         ifstream infile("student.dat");
         char name[8],id[8];
         int math,eng,computer;
        
         int i = 0;
         char c;
         while((c=infile.get())!=EOF)
           {
             
             infile>>name>>id>>math>>eng>>computer;
             cout<<"name:  "<<name<<endl;
             cout<<"id:  "<<id<<endl;
             cout<<"math:  "<<math<<endl;
             cout<<"eng:  "<<eng<<endl;
             cout<<"computer:  "<<computer<<endl;
    
    
         }
         infile.close();
    
     }
    
    
    
      

    看似无问题,但每次从文件中读出的结果总会多出一组数据(最后一组数据会读出两边),找了好久都没有发现,经网上查阅资料总结为以下几点:

       1.由于采用的写入语句为“outfile<<name<<" "<<id<<" "<<math<<" "<<eng<<" "<<computer<<endl;“,即每次写完一组数据后,都会向文件中写入一个回车符,所以在读文件的时候,当读到最后一组数据时,读完之后,文件中还有一个回车符没有读出来,此时判断eof()并不为-1,故还会再进行一次读操作;这次读操作实际上并没读到什么,但还有一个输出,输出的为上次读操作的结果,故最后一组数据显示两次。

     2.eof()判断的是文件中所有的字符包括回车,只有当文件中什么字符都没有了,才会返回-1,到达文件的末尾。

     3.故再使用infile和outfile对文件进行操作时,应该先读再判断(例如,本例中,先读一个name,再进行判断,当遇到最后一个回车符时,会有infile>>name这个操作正好解决了它这样能保证你写的和读的内容是一样的。

    4.所以,较好的读文件方式如下

    infile>>name;
    while((c=infile.get())!=EOF)
           {
             
             infile>>id>>math>>eng>>computer;
             cout<<"name:  "<<name<<endl;
             cout<<"id:  "<<id<<endl;
             cout<<"math:  "<<math<<endl;
             cout<<"eng:  "<<eng<<endl;
             cout<<"computer:  "<<computer<<endl;
    
            infile>>name;
       
    
         }
    
  • 相关阅读:
    Vue 2.x windows环境下安装
    VSCODE官网下载缓慢或下载失败 解决办法
    angular cli 降级
    Win10 VS2019 设置 以管理员身份运行
    XSHELL 连接 阿里云ECS实例
    Chrome浏览器跨域设置
    DBeaver 执行 mysql 多条语句报错
    DBeaver 连接MySql 8.0 报错 Public Key Retrieval is not allowed
    DBeaver 连接MySql 8.0报错 Unable to load authentication plugin 'caching_sha2_password'
    Linux系统分区
  • 原文地址:https://www.cnblogs.com/wangkundentisy/p/3665207.html
Copyright © 2011-2022 走看看