在字符串数组中动态创建和存储数据
Dynamically creating and storing data in a string array
我正在使用libconfig c++库来获取存储的数据,并且需要在不知道将通过配置文件传递的变量数量的情况下将该数据存储在c ++的字符串数组中。我知道这在 c++ 中是不可能的,但我正在尝试找到执行此操作的最佳实践,而其他解决方案似乎对我正在做的事情没有实际意义。下面是我尝试获取字符串文件类型并将所有结果分别存储在字符串数组中的代码部分。
try {
for (int i = 0; i < cfg.getRoot()["files"].getLength(); ++i) {
// Only output the record if all of the expected fields are present.
string filetype;
if (!(cfg.getRoot()["files"][i].lookupValue("filetype", filetype)))
continue;
cout << filetype << endl;
}
}
catch (const SettingNotFoundException &nfex) {
// Ignore.
}
对于您现在可能遇到的脸掌,我是一名仍在学习绳索的大学生,并且目前正在进行个人项目,并且正在
提前完成我的课程。我相信您的代码只需进行最少的更改即可按照您需要的方式运行。您只需要一个std::vector<std::string>
来包含您从循环中记录的所有字段:
std::vector<std::string> filetypes;
try {
for (int i = 0; i < cfg.getRoot()["files"].getLength(); ++i) {
// Only output the record if all of the expected fields are present.
std::string filetype;
if (!(cfg.getRoot()["files"][i].lookupValue("filetype", filetype)))
continue;
//The use of std::move is optional, it only helps improve performance.
//Code will be logically correct if you omit it.
filetypes.emplace_back(std::move(filetype));
}
}
catch (const SettingNotFoundException &nfex) {
// Ignore.
}
//Proof that all values have been properly stored.
for(std::string const& filetype : filetypes) {
std::cout << filetype << std::endl;
}
我不知道cfg.getRoot()["files"]
上的返回类型是什么,但存储该对象以提高代码的可读性可能是值得的:
std::vector<std::string> filetypes;
try {
//One of these is correct for your code; I don't know which.
//auto & files = cfg.getRoot()["files"];
//auto const& files = cfg.getRoot()["files"];
//I'm assuming this is correct
auto files = cfg.getRoot()["files"];
for (auto const& entry : files) {
// Only output the record if all of the expected fields are present.
std::string filetype;
if (!(entry.lookupValue("filetype", filetype)))
continue;
//The use of std::move is optional, it only helps improve performance.
//Code will be logically correct if you omit it.
filetypes.emplace_back(std::move(filetype));
}
}
catch (const SettingNotFoundException &nfex) {
// Ignore.
}
//Proof that all values have been properly stored.
for(std::string const& filetype : filetypes) {
std::cout << filetype << std::endl;
}
相关文章:
- 使用 char* 存储数据和产生的错误
- 我可以存储数据的地方/C++,Linux,QtCreator
- 如何在共享库的整个生命周期内存储数据
- 在字符串数组中动态创建和存储数据
- 用指向文件的指针存储数据结构
- 如何存储数据/我们如何获取存储在 unordered_map c++11 中存储桶中的数据
- 存储数据的对象和存储指向数据的智能指针的对象
- C++读取文本文件并存储数据
- Cocos2dx: 无法存储数据?
- 如何在每次循环迭代期间生成向量,存储数据,然后删除该向量?
- 尝试从每个预期数据之间有多个空间的文件中读取和存储数据
- 存储数据列表并自动分配给结构的最佳方法是什么
- QT MAC应用程序存储数据路径
- 动态分配存储数据在堆中的随机位置中
- 鸟类调查中的项目在代码中遇到问题.如何像数据库系统一样存储数据
- 可以在C 中永久存储数据中的数据
- 用于存储数据的结构和外部二进制文件
- 使用 char 数组存储数据
- 在结构中读取和存储数据
- 尝试在结构中存储数据时出现堆分配错误