Add new branch filled by a series of variables to tree

Dear experts

I want to add some new branches to a tree and then save it as root file. But my result of executing my code is that the root file contain some trees. And the second tree contains both the variables of the first tree and the data I want to add the new branch or tree.

My code is as follow and the data file is at the bottom. I don’t know where the code goes wrong. Many thanks in advance.

struct DATA
{
	float x, xhigh, xlow,
		  y1, dy1m, dy1p,dy1msy,dy1psy,
		  y2, dy2m, dy2p,dy2msy,dy2psy;
};

void read_from_file(TFile *totaldata,/* TTree * tree,*/ TTree & tree,const char * brp, const char* datap)
{	DATA data;
	
//	tree->Branch(brp,&data,"x/F:xhigh:xlow:y1:dy1m:dy1p:dy1msy:dy1psy:y2:dy2m:dy2p:dy2msy:dy2psy");
	tree.Branch(brp,&data,"x/F:xhigh:xlow:y1:dy1m:dy1p:dy1msy:dy1psy:y2:dy2m:dy2p:dy2msy:dy2psy");
		  
	ifstream inf1(datap);

	int num=0;

	if(!inf1.is_open())
		std::cout<<"Error"<<std::endl;
	while(!inf1.eof()){
		inf1>>data.x>>data.xlow>>data.xhigh
		    >>data.y1>>data.dy1p>>data.dy1m>>data.dy1msy>>data.dy1psy
                    >>data.y2>>data.dy2p>>data.dy2m>>data.dy2msy>>data.dy2psy;
//		tree->Fill();
		tree.Fill();
		num++;
	}

	tree.Write();
//	tree->Write();
	cout << num << endl;
}



void hw_modified()
{	
	
	TFile *totaldata= new TFile("totaldata.root","recreate");
//	TTree *tree= new TTree("tree","tree_for_data");
	TTree tree("tree","tree_for_data");	
	read_from_file(totaldata,tree,"Pi","Pi.txt");	
	read_from_file(totaldata,tree,"K","K.txt");
	read_from_file(totaldata,tree,"Proton","Proton.txt");
	
	totaldata->Close();
}

data.zip (3.5 KB)

Try: TBranch *b = tree.Branch(brp, &data, "..."); // ... b->Fill(); // instead of tree.Fill();

Hi, Wile. I tried your method. It seems the same, file contains three trees. And then I move the sentence “tree.Write()” to the function hw_modified. This time, the root file contains one tree, but no entries. After that, I replace the object tree by a TTree pointer. And the data is written to root file. I am puzzled. Is it the matter of object lifetime? The object is defined in the main function and likely to exist until the write procedure. And I use TBrowser() to look over the variables on the tree. The mean value is not equivalent to the value when I save only one branch. It puzzled me as well.

Many thanks in advance.

Aux;1 aux;2 aux3;

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.