write/read string in a TTree (cern root)

IljaBek picture IljaBek · Aug 10, 2011 · Viewed 8.8k times · Source

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);
tTShowerHeader->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?

Answer

Jan Hudec picture Jan Hudec · Aug 10, 2011

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).