在树(cern根)中写/读字符串

write/read string in a TTree (cern root)

本文关键字:字符串 中写 cern 在树      更新时间:2023-10-16

保存字符串到tree

std::string fProjNameIn,  fProjNameOut;
TTree *tTShowerHeader;
tTShowerHeader = new TTree("tTShowerHeader","Parameters of the Shower");
tTShowerHeader->Branch("fProjName",&fProjNameIn);
tTShowerHeader->Fill();

我正在尝试做以下事情

fProjNameOut = (std::string) tTShowerHeader->GetBranch("fProjName");

不能编译,但是

std::cout << tTShowerHeader->GetBranch("fProjName")->GetClassName() << std::endl;

告诉我,这个分支的类型是string

是否有标准的方法从根树中读取std::字符串?

解决方案如下:

假设你有一个ROOT文件,你想在其中保存一个std::字符串。

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

访问:

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

打印到标准输出:

std::cout << some_str_pt->c_str() << std::endl;

您正在调用tTShowerHeader->GetBranch("fProjName") ->并且它正在编译。这意味着tTShowerHeader->GetBranch()的返回类型是一个指针

此外,您在该指针上调用GetClassName()并进行编译,因此它是指向类类型的指针。

甚至,std::string没有GetClassName()方法,所以它是而不是 std::string*。的确,似乎是TBranch *。你必须找到合适的方法来获得文本。

PS:忘记在c++中使用C风格的强制转换。c风格的强制转换是,因为它会根据类型的不同做不同的事情。请使用受限制的static_castdynamic_castconst_cast或函数样式强制转换(如果您确实需要,也可以使用reinterpret_cast,但这种情况应该非常少见)。

好的,这花了一些时间,但我想出了如何从树中获取信息。您不能直接返回信息,它只能通过给定的变量返回。

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"

在root中,tree类存储了用于输入的变量的地址。使用GetEntry()将用存储在tree中的信息填充相同的变量。您还可以使用tTShowerHeader->Print()来显示每个分支的整体数量。