Search code examples
c++root-framework

Using the index of a for loop in a string


I have a little problem but have no idea how to solve it. I want to use the index from a for loop to get the different histograms in my root files. I have read the root files correctly and I know that the error that I get has something to do with the index in my string. But I don’t know how to do it correctly. I tried using Form() but it does not work.

The names of my histograms in the root files are: bin_1_h0_01, bin_2_h0_01 and so on until bin_512_h0_01. That is the reason why I need the index.

TFile* simHistograms = TFile::Open("sim_output_histograms.root", "READ");
TFile* dataHistograms = TFile::Open("data_output_histograms.root", "READ");

for(int i {1}; i < 513; i++){

    TH1F* sim = (TH1F*)simHistograms->Get(Form("bin_%i_h0_01", i));
    TH1F* data = (TH1F*)dataHistograms->Get(Form("bin_%i_h0_01", i));

    sim->SetDirectory(0);
    data->SetDirectory(0);

    ...
}

The error message i get is:

/../analyzeData_plot.cpp:33:9: warning: null passed to a callee that requires a non-null argument [-Wnonnull]
        sim->SetDirectory(0);
        ^~~

ROOT Version: 6.28/04 Platform: Ubuntu 20.04.2 Compiler: g++ 9.4.0



Solution

  • yes because,you are passing a null argument to the SetDirectory() function, and this error is likely caused by the fact that the histogram objects sim and data are not being retrieved correctly from the root files, so you can edit the Form() function call to correctly format the histogram names because the Form() function returns a formatted string, and you can use it directly as the argument for Get()!

    let me show you how :

    TFile* simHistograms = TFile::Open("sim_output_histograms.root", "READ");
    TFile* dataHistograms = TFile::Open("data_output_histograms.root", "READ");
    
    for (int i = 1; i <= 512; i++) {
        TString histName = Form("bin_%d_h0_01", i);
    
        TH1F* sim = (TH1F*)simHistograms->Get(histName);
        TH1F* data = (TH1F*)dataHistograms->Get(histName);
    
        if (sim && data) {
            sim->SetDirectory(0);
            data->SetDirectory(0);
    
            //you can use the histograms as needed
        } else {
            //handle the case where the histograms are not found
        }
    }
    
    simHistograms->Close();
    dataHistograms->Close();