首页 > 解决方案 > 在部分txt文档中查找信息并将它们存储在变量中

问题描述

我有一个包含信息的大型 .txt 文档。它的结构是这样的:

编号:54670
性别:男
姓名:约翰·多伊
地址:呸呸呸呸
电子邮件:JohnDoe@.com

我正在尝试创建一个允许输入 ID 的程序。程序会在文本文档中找到 ID,然后将 ID、性别、姓名、地址等存储在变量中。我可以搜索 ID 并打印以下行。但是我不知道如何存储每行的特定部分,并且在找到 ID 后只存储来自 5 行的信息。这就是我到目前为止所拥有的一切。任何指针将不胜感激。在过去的几周里,我刚刚开始自学编码。所以你们都是这么棒的资源。

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();

标签: c++variablessearchifstream

解决方案


你可以创建

map<int,list<string>>

稍后解析您的文件并拆分每一行并将这些值存储在您的地图中

//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];

推荐阅读