write/read string in a TTree (cern root)
after saving a string into a TTree
std::string fProjNameIn, fProjNameOut;
TTree *tTShowerHeader;
tTShowerHeader = new TTree("tTShowerHeader","Parameters of the Shower");
tTShowerHeader->Branch("fProjName",&fProjNameIn);
tTS开发者_Go百科howerHeader->Fill();
I'm trying to do the following
fProjNameOut = (std::string) tTShowerHeader->GetBranch("fProjName");
which does not compile, though
std::cout << tTShowerHeader->GetBranch("fProjName")->GetClassName() << std::endl;
tells me, this Branch is of type string
is there a standard way to read a std::string from a root tree?
The solution follows below.
Imagine you have a ROOT file and you want to save an std::string to it.
TTree * a_tree = new TTree("a_tree_name");
std::string a_string("blah");
a_tree->Branch("str_branch_name", &a_string); // at this point, you've saved "blah" into a branch as an std::string
To access it:
TTree * some_tree = (TTree*)some_file->Get("a_tree_name");
std::string * some_str_pt = new std::string();
some_tree->SetBranchAddress("str_branch_name", &some_str_pt);
some_tree->GetEntry(0);
To print to standard output:
std::cout << some_str_pt->c_str() << std::endl;
Hope this helps.
You are calling tTShowerHeader->GetBranch("fProjName")
-> and it compiles. That means that return type of tTShowerHeader->GetBranch()
is a pointer.
Moreover, you are calling GetClassName()
on that pointer and it compiles, so it's a pointer to a class type.
Even more, the std::string
does not have a GetClassName()
method, so it's not a std::string*
. Indeed, it seems it is TBranch *
. You must find appropriate method that will give you the text.
PS: Unlearn to use C-style cast in C++. C-style cast is evil, because it will do different things depending on what the type happens to be. Use the restricted static_cast
, dynamic_cast
, const_cast
or function-style casts instead (and reinterpret_cast
if you really need that, but that should be extremely rare).
Ok, this took a while but I figured out how to get the information from the tree. You cannot directly return the information, it can only be returned through the variable it was given in.
std::string fProjNameIn, fProjNameOut;
TTree *tTShowerHeader;
fProjnameIn = "Jones";
tTShowerHeader = new TTree("tTShowerHeader","Parameters of the Shower");
tTShowerHeader->Branch("fProjName",&fProjNameIn);
tTShowerHeader->Fill();//at this point the name "Jones" is stored in the Tree
fProjNameIn = 0;//VERY IMPORTANT TO DO (or so I read)
tTShowerHeader->GetBranch("fProjName")->GetEntries();//will return the # of entries
tTShowerHeader->GetBranch("fProjName")->GetEntry(0);//return the first entry
//At this point fProjNameIn is once again equal to "Jones"
In root the TTree class stores the address to the varriable used for input into it. Using GetEntry() will fill the same variable with the information stored in the TTree. You can also use tTShowerHeader->Print() to display the number of entires for each branch.
精彩评论