[英]How to look for certain keywords in a document and read them into the program (C++)
I've been given a document, from which I have to read certain Information into my C++ program that are preceded by appropriate Keywords looking like this:我得到了一份文件,我必须从中读取某些信息到我的 C++ 程序中,这些信息前面有适当的关键字,如下所示:
...
*useless information*
...
KEYWORD_A : VALUE_A
...
*useless information*
...
KEYWORD_B : VALUE_B
...
What would be the most efficient/correct way for filtering these Keywords, that do not have to appear in a certain order?过滤这些不必以特定顺序出现的关键字的最有效/正确方法是什么? I currently use following scheme to do so我目前使用以下方案这样做
std::string content_of_line = "";
while(content_of_line.find("KEYWORD_A") == std::string::npos){
std::getline(file,content_of_line);
}
std::stringstream stream(content_of_line);
stream >> variable_a;
std::getline(file,content_of_line);
while(content_of_line.find("KEYWORD_B") == std::string::npos){
std::getline(file,content_of_line);
}
stream.clear();
stream << content_of_line;
stream >> variable_b;
// and so on....
This, however, produces a lot of redundant code and also relies on a specific order of the keywords (which doesnt necessarily have to exist)... I hope you can show me a much nicer way of solving my problem.但是,这会产生大量冗余代码,并且还依赖于关键字的特定顺序(不一定必须存在)......我希望你能告诉我一个更好的方法来解决我的问题。 Thank you very much in advance for trying to help me on my problem!非常感谢您尝试帮助我解决我的问题!
Ok, I'll take a shot好的,我去拍
#include <fstream>
#include <iostream>
#include <string>
#include <unordered_map>
int main()
{
std::ifstream inp("inp.txt");
std::string word;
using valueType = std::string;
//Assuming keywords only appear once in the file
std::unordered_map<std::string, valueType> keywords {{"KEYWORD_A", ""},{"KEYWORD_B", ""},};
while(inp>>std::ws>>word) {
if(keywords.find(word) != keywords.cend()) {
//Assuming schema of lines with keywords is KEY : VALUE
inp.ignore(std::numeric_limits<std::streamsize>::max(), ':');
inp>>std::ws>>keywords[word];
}
}
for(const auto& pair: keywords) {
std::cout<<pair.first<<' '<<pair.second<<'\n';
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.