在树(cern根)中写/读字符串
write/read string in a TTree (cern root)
保存字符串到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_cast
、dynamic_cast
、const_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()来显示每个分支的整体数量。
相关文章:
- 如何在C++中从字符串中分割字符
- 从C字符串中获取奇怪的字符串长度
- 如何用转义符替换字符串中的所有特殊字符
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 使用正则表达式regex_search在字符串中查找字符串
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 如何从给定字符串中删除第二次和第三次出现的$
- 如何检查一个c++字符串中有多少相同的字符/数字
- C++.我想将更改后的特定字符行保存在字符串中
- 使用std::mt19937从字符串中返回一个随机单词
- 是否可以从格式字符串中检索"width"
- 我应该如何修改此代码以使用给定字符串中的字母打印菱形图案
- 字符串中int的加法运算
- 未获得字符串中的预期输出
- 从字符串中获取结构的大小
- 由cin中的字符串中未捕获空白引起的分割错误
- 如何在yaml-cpp中写一个版本字符串作为文字(不是字符串)
- 如何在先前读取行中找到一些单词并在C 中的输出读/写字符串中删除它
- 在树(cern根)中写/读字符串
- 在文件中写入时,文件未显示字符串的最后一个字符