eof的使用

本文探讨了使用C++从文件中读取字符时遇到的一个常见问题:为何最后一个字符会被重复输出,并提供了三种不同的解决方案来避免这个问题。
    假设有一文件in.data,其内容为123,现要读取并输出其内容,程序如下:
#include <iostream>
#include 
<fstream>
using namespace std;

int main()
{
        
char c;
        fstream  
in;       
        in.open("in.data");
 
        
while(!in.eof())
        
{
                  in
>>c;
                  cout
<<c;
        }
           in.close();
       return 0;
}
输出: 1233

为什么最后一个字符3会多输出一次呢?
因为当读取3之后,程序不会立刻检测到EOF,必须再次读取一次,而后才能识别到EOF,while循环执行了4次,所以会再次输出3。
    可以作如下几种改进:
 1.
#include <iostream>
#include 
<fstream>
using namespace std;

int main()
{
        
char c;
        fstream  
in;          
        
in.open("in.data");
        
        
in>>c;
        
while(!in.eof())           // 循环体执行了3次
        
{
                 cout
<<c;
                  
in>>c;
        }

        
in.close();

        
return 0;
}

2.
#include <iostream>
#include 
<fstream>
using namespace std;

int main()
{
        
char c;
        fstream  
in;          
        
in.open("in.data");

        
while(1)
        
{
                 
in>>c;
                 
if(in.eof())
                           
break;
                 cout
<<c;
        }

        
in.close();

        
return 0;
}
3.
//  input from console
#include <iostream>
#include 
<fstream>
using namespace std;

int main()
{
        
char c;
        
        
while(scanf("%c"&c)!=EOF) 
       
{
                 cout
<<c;
        }


        
return 0;
}

   
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值