Hello rooters, I hope you’re doing well!!
I’m trying to read a data file and use the read data to fill a TH1F histogram, but I’m having some strange erros. I followed the steps of this topic To fill a histogram by reading text file but i just cant get it done right. I’ve write my code in two versions, one using a for loop and the another one using a while loop. Here is the two version:
While version:
#include <iostream>
#include <fstream>
/*Reading a data file and creating a histogram with the data: while version*/
void pte_distribution()
{
TH1F *hist = new TH1F("hist","Pt Distribution(e)",1000,0,100); //Create the histogram called hist
ifstream pt_e("pt_e.txt");//Load the data file
int pt; //declare the variable to store the value of the momentum that will be read from the data file later on
while(pt_e >> pt){ //while there is lines to be read...
hist -> Fill(pt); //...the Fill command will fill the histogram hist with the values of pt
}
TCanvas * c1 = new TCanvas("c", "c", 800, 600); // Create a canvas 800x600
hist->Draw("E"); //Draw the histogram hist
c1->Update(); // Update the canvas created
c1->SaveAs("Pt Distribution(e).pdf"); //Saves the histogram
}
For version:
#include <iostream>
#include <fstream>
/*Reading a data file and creating a histogram with the data: for version*/
void pte_distribution()
{
TH1F *hist = new TH1F("hist","Pt Distribution(e)",1000,0,100); //Create the histogram called hist
ifstream pt_e("pt_e.txt");//Load tge data file
int pt; //declare the variable to store the value of the momentum that will be read from the data file later on
for (int i = 0; i < 1000000; ++i)//My data file have 1000000 lines...
{
pt_e >> pt;
hist->SetBinContent(i,pt);
}
TCanvas * c1 = new TCanvas("c", "c", 800, 600); // Create a canvas 800x600
hist->Draw("E"); //Draw the histogram hist
c1->Update(); // Update the canvas created
c1->SaveAs("Pt Distribution(e).pdf"); //Saves the histogram
}
While version result:
For version result:
Ps1: My data file is a .txt file
Ps2: as you can see, my for version produced an empty histogram. The same problem appeared in the topic that I’ve posted here, but i don’t know the reason why.
Thank you very much for all the help,
Cauê