我有一个包含信息的大型 .txt 文档。它以这种格式构建:
ID: 54670 Gender: M Name: John Doe Address: Blah Blah Blah Email: JohnDoe@.com
I'm trying to create a program that allows one to enter the ID. The program will find the ID in the text document and then store the ID,Gender,Name,Address, etc.. in variables. I can search for the ID and print following lines. But I'm lost on how to store particular parts of each line and only storing the info from say 5 lines after finding the ID. This is all i have so far. Any pointers would be much appreciated. I have just started teaching myself to code in the last couple weeks. So you are all such a great resource.
struct userInfo
{
int id;
char gender;
std::string name,address,email;
};
std::string search,line;
std::ifstream inFile;
inFile.open("iData.txt");
if (!inFile)
{
std::cout << "Was unable to open file!";
return 1;
}
std::cout << "Enter I.D" << std::endl;
std::getline(std::cin, search);
while (inFile.good())
{
std::getline(inFile, line);
if (line.find(search) != std::string::npos)
{
std::cout << line << std::endl;
}
}
inFile.close();
最佳答案
你可以创造
map<int,list<string>>
稍后解析您的文件一次并拆分每一行并将这些值存储在您的 map 中
//Example code to fetch data from line
std::getline(inFile, line);
int pos = line.find(":");
std::string val = line.substr(pos+1, line.length());
之后你就可以使用
List<string> details = map.find[id];
关于c++ - 在txt文档的部分内容中查找信息并将其存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55039914/