eof的使用

    假设有一文件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;
}

   

你可能感兴趣的:(c,input,iostream)