从文本文件中查找并提取数据
我正在尝试搜索文本文件并在标题后提取数据。但是,我遇到了一些迭代器问题,我不知道如何克服。
这是一个示例文本文件:
继电器状态 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
并让它返回一个带有 {0,0,0,0,0,0,0,0,...} 的 std::vector。
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::search 是一个不明确的调用,我将如何解决这个问题?
- ifs.seekg(iit) 不合法,我该如何使 iit 成为有效的参数?
谢谢。
I'm tring to search a text file and extract the data after a heading. However, I've got some issues with iterators that I don't know how to overcome.
This is a sample 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
Ideally, I'd like to call LoadData<bool> something.LoadData("Relay States");
and have it return an std::vector with {0,0,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;
}
From what I understand, the main problems with my code are:
- std::search is an ambiguous call, how would I go about fixing this?
- ifs.seekg(iit) is not legal, how would I go about making iit a valid argument?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,我认为你对 std::search 的参数问题
应该是
for 循环中的
ifs.seekg(iit)
行不好,因为 seeg 需要一些streampos
类型的偏移量不是迭代器。所以它应该是ifs.seekg(0)
Well I think your args to std::search is problem
should be
as for line :
ifs.seekg(iit)
infor
loop isn't good , since seekg expects some offset of typestreampos
not an iterator. so it should beifs.seekg(0)
像这样的事情怎么样:
How about something like this: