Reading in a list of variables from a txt file to store as TTrees

Dear ROOT experts,

For a .txt file which contains information about name, type, dimension and value of variables:

Particle Detector Stats
JPsiCounts%I1=4;
OmegaCounts%I1=1;
calibratePower%F1=520.6;
coreReadout%D5 = 4.2,7.1,5.6,8.2,9.7

i.e. first entry is Int_t JPsiCounts = 4
last entry is Double_t coreReadout[5] = {4.2,7.1,5.6,8.2,9.7}

How can one read these variables from the text into root and store them as TTrees for an arbitrary txt file (i.e. the names of the variables in the txt file can be different depending on the txt file)?

Here’s an approach I tried:

#include <iostream>
#include <istream>
#include <sstream>
#include <fstream>

void configToRoot()
{
  
  std::ifstream inputFile("example.txt");
  std::string line;
  Int_t lineNumber = 0;

  TFile *myfile = new TFile("test.root","RECREATE");

  Int_t value = 0;
  Int_t value2 = 0;
  Int_t value3 = 0;
  
  while(getline(inputFile, line)) // while reading the file
    {
      if(line.size() == 0 || line[0] == '*') // For the first character of a line: line must be >0
	{
	  continue; // i.e. skip line and go to next line immediately
	}
      
      for(Int_t lineElement = 0; lineElement<line.size(); lineElement++)
	{
	  
	  if(line[lineElement-4] == '%' && line[lineElement-1] == '=') // 
	    {

	      if(line[lineElement-2] == '1') // for 1D
		// will do an array part later
		{
	      
		  if(line[lineElement-3] == 'I') // for ints
		    {

		      if(lineNumber == 1)
			{
			  TTree *tree = new TTree("myTree","A ROOT tree");
			  value = line[lineElement];
			  cout << value;
			  tree->Branch("value",&value,"value/C");
			  tree->Fill();
			}

		      else if(lineNumber == 2)
			{
			  TTree *tree2 = new TTree("myTree2","A ROOT tree 2");
			  value2 = line[lineElement];
			  cout << value2;
			  tree2->Branch("value2",&value2,"value2/C");
			  tree2->Fill();
			}
		      
		      
		      else if(lineNumber == 3)
			{
			  TTree *tree3 = new TTree("myTree3","A ROOT tree 3");
			  
			  value3 = line[lineElement];
			  cout << value3;
			  tree3->Branch("value3",&value3,"value3/C");
			  tree3->Fill();
			}
		      
		    }
		  /*
		  else if(line[lineElement-3] == 'F') // for floats
		    {
		      value = line[lineElement];
		      cout << "value = " << value;
		      tree->Branch("value",&value,"value/C");
		      tree->Fill();
		      myfile->Write();
		    }
		  */
		}
	    }
	   
	  else
	    {
	      cout << line[lineElement];
	    }
	  
	}

      cout << endl;

      lineNumber++;
    }
      return;
 }

However, I can’t seem to make the read-in names vary (see above for the arbitrary text file mention) each time, automate the process of making the trees from each line, and selecting the whole object, not just the first character after =.

Any advice is greatly appreciated,

Luke

Have you tried this:

root.cern/doc/master/classTTree … f1d3bdc120

?