[英]How to look for certain keywords in a document and read them into the program (C++)
我得到了一份文件,我必須從中讀取某些信息到我的 C++ 程序中,這些信息前面有適當的關鍵字,如下所示:
...
*useless information*
...
KEYWORD_A : VALUE_A
...
*useless information*
...
KEYWORD_B : VALUE_B
...
過濾這些不必以特定順序出現的關鍵字的最有效/正確方法是什么? 我目前使用以下方案這樣做
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....
但是,這會產生大量冗余代碼,並且還依賴於關鍵字的特定順序(不一定必須存在)......我希望你能告訴我一個更好的方法來解決我的問題。 非常感謝您嘗試幫助我解決我的問題!
好的,我去拍
#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.