c ++ ifstream两次打印文件中的最后一项

时间:2017-01-02 23:47:21

标签: c++ ifstream

我想从文件afile.dat中读取数据,然后将数据打印到屏幕上。该文件的内容如下:

Max
20

为了将这两个项目打印到屏幕上,我编写了以下C ++程序:

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


int main () 
{

   char data[100];

   ifstream infile; 
   infile.open("afile.dat"); 

   cout << "Reading from the file" << endl; 

   while(infile){   
        infile >> data;
         cout << data << endl;  
   }

   infile.close();

   return 0;
}

该程序的输出是:

Max
20
20

为什么“20”打印两次?

0 个答案:

没有答案
相关问题