eof()は使うのに注意が必要(2)

例えば、あなたが4行からなるテキストファイルを持っていたとしましょう。

1 2.0
2 2.2
3 2.4
4 2.6

correct

// code correct
{ 
  ifstream finput("owondata3.txt");
  const Int_t icount_max=16;
  Int_t icount=0;
  Double_t data1[icount_max], data2[icount_max];
  
  while(icount < icount_max) { 
    finput >> data1[icount] >> data2[icount];
    std::cout << icount << ", " << data1[icount] << ", " << data2[icount] << std::endl;
    if(finput.eof()) break;
    icount++;
  }
  std::cout << "icount = " << icount << std::endl;

  TCanvas *c1 = new TCanvas("c1","Test",200,100,800,600);
  TGraph *g = new TGraph(icount, data1, data2);
  g->SetMarkerStyle( 20 );
  g->SetMarkerSize( 2.0 );
  g->Draw("AP");
}
% root correct.cc 
0, 1, 2
1, 2, 2.2
2, 3, 2.4
3, 4, 2.6
4, 0, 0
icount = 4
0, 1, 2
1, 2, 2.2
2, 3, 2.4
3, 4, 2.6

wrong

// code wrong
{
  ifstream finput("owondata3.txt");
  const Int_t icount_max=16;
  Int_t icount=0;
  Double_t data1[icount_max], data2[icount_max];

  while(! finput.eof() ) {
    finput >> data1[icount] >> data2[icount];
    std::cout << icount << ", " << data1[icount] << ", " << data2[icount] << std::endl;
    icount++;
  }
  std::cout << "icount = " << icount << std::endl;

  for(int i=0;i<icount;i++) {
    std::cout << i << ", " << data1[i] << ", " << data2[i] << std::endl;
  }

  TCanvas *c1 = new TCanvas("c1","Wrong",200,100,800,600);
  TGraph *g = new TGraph(icount, data1, data2);
  g->SetMarkerStyle( 20 );
  g->SetMarkerSize( 2.0 );
  g->Draw("AP");
}
% root wrong.cc 
0, 1, 2
1, 2, 2.2
2, 3, 2.4
3, 4, 2.6
4, 0, 0
icount = 5
0, 1, 2
1, 2, 2.2
2, 3, 2.4
3, 4, 2.6
4, 0, 0

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.