c++ - 在txt文档的部分内容中查找信息并将其存储在变量中

标签 c++ variables search ifstream

我有一个包含信息的大型 .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/

相关文章:

javascript - 从 HTML 类内部访问 Ruby 变量并在 JS 函数中使用它

css - 如何连接变量名?

mysql - 复杂的搜索设计

php - 突出显示段落中的关键字

c++ - 重载运算符+/char* ch1 + char* ch2

c++ - 从新线程调用时出现 COM 0x8001010E 错误

c++ - 分配给函数调用返回的指针

c++ - 如何使用 TVS_CHECKBOXES 样式删除特定 TreeView 项上的复选框

javascript - 从外部调用jquery函数内的变量

具有结果选择和复制功能的 Linux 搜索工具