在TXT文档的一部分中查找信息并将其存储在变量中

Finding information in parts of txt document and storing them in variables

本文关键字:变量 存储 查找 TXT 文档 一部分 信息      更新时间:2023-10-16

我有一个大的.txt文档保留信息。它以这种格式结构:

ID:54670性别:m名称:约翰·多伊(John Doe)地址:等等等等电子邮件: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();

您可以创建

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

您可以读取一次文件并将信息保存在地图中,因此当给定ID时,您可以获取信息映射[id] .gender