从文本文件中查找和提取数据
Find and extract data from a text file
我正在字符串中搜索文本文件并提取标题后的数据。然而,我在迭代器方面遇到了一些问题,我不知道如何克服这些问题。
这是一个示例文本文件:
Relay States 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
理想情况下,我想调用LoadData<bool> something.LoadData("Relay States");
,并让它返回一个std::vector,带有{0,0,0,0,0,0,…}。
template<typename T> std::vector<T> CProfile::LoadData(const std::string& name)
{
std::ifstream ifs(FILE_NAME);
std::vector<T> data;
std::istreambuf_iterator<char> iit = std::istreambuf_iterator<char>(ifs);
std::search(iit, ifs.eof(), name.begin(), name.end());
std::advance(iit, name.size() + 1);
T buffer = 0;
for(ifs.seekg(iit); ifs.peek() != 'n' && !ifs.eof(); data.push_back(ifs))
{
ifs >> buffer;
data.push_back(buffer);
}
return data;
}
据我所知,我的代码的主要问题是:
- std:搜索是一个模棱两可的调用,我该如何解决这个问题
- 如果seekg(iit)不合法,我该如何使它成为一个有效的论点
谢谢。
我认为你对std::search的args是的问题
std::search(iit, ifs.eof(), name.begin(), name.end());
应该是
std::search(iit, std::istreambuf_iterator<char>(), name.begin(), name.end());
至于第行:for
循环中的ifs.seekg(iit)
并不好,因为seekg希望streampos
类型的偏移量不是迭代器。所以它应该是ifs.seekg(0)
这样的东西怎么样:
template<typename T> std::vector<T> CProfile::RealLoadData(std::istream &is)
{
std::string line;
std::vector<T> data;
while (std::getline(is, line))
{
if (line.empty())
break; // Empty line, end of data
std::istringstream iss(line);
T temp;
while (iss >> temp)
data.push_back(temp);
}
return data;
}
template<typename T> std::vector<T> CProfile::LoadData(const std::string& name)
{
std::string line;
std::ifstream ifs(FILE_NAME);
while (std::getline(ifs, line))
{
if (line == name)
{
// Found the section, now get the actual data
return RealLoadData<T>(ifs);
}
}
// Section not found, return an empty vector
return std::vector<T>();
}
相关文章:
- JPG-如何从ICC配置文件部分APP2读取/提取数据
- 如何从多维向量中提取数据
- 从异构列表中提取数据
- 从 Windows 中的其他应用程序 GUI 中提取数据
- 如何从 qwebengineview qt5.9 中提取数据
- 如何从shared_ptr<T&>的引用中提取数据
- 从自定义结构数组中提取数据
- 无法从结构数组 C++ 中提取数据
- 用字符串::擦除在C 中提取数据
- C 从结构Deque提取数据
- 如何从 char[] 字符串中提取数据
- 用C++从字符串中优雅地提取数据
- 如何从用|分隔的txt文件中提取数据
- 如何从结构数组中提取数据
- 如何使用 C++11 <thread> 设计从源中提取数据的系统
- 从数据库中提取数据时使用QVariant的正确方法
- 提取数据范围的分隔符
- 从文本文件中查找和提取数据
- 是否有用于从HTML页面中提取数据的库
- 使用Boost::python从嵌入式python中提取数据