文件解析代码需要注意

File parsing code need attention

本文关键字:代码 文件      更新时间:2023-10-16

我有这样的文件

I am a student xyz in university"|USA|" in first year.
I am a student abc in university"|America|" in first year.
I am a student asd in university"|Italy|" in first year.

我必须解析文件并仅从文件中提取大学名称以及 xyz,abc,asd所以我写了以下代码

#include <fstream>
#include <string>
#include <iostream>
bool ParseLine(const std::string& line, std::string& key, std::string& value);
class Demo
{
public:
    typedef struct _Data 
    {
        std::string university;
        std::string name;
    } Data;
    Data data;
};
int main()
{
    std::ifstream ifs("Ca.txt");
    std::string line;
    std::string key;
    std::string value;
    Demo obj;
    while(!ifs.eof())
    {
        std::getline(ifs, line);
        if (ParseLine(line, key, value))
        {
            if (0 == key.compare("student"))
            {
                obj.data.name = value;
            }
             else if (0 == key.compare("university"))
            {
                obj.data.content = value;
            }
            else
            {
                std::cerr<<"Unknow key:" << key << std::endl;
            }
        }
    }
    return 0;
}
bool ParseLine(const std::string& line, std::string& key, std::string& value)
{
    bool flag = false;
    if (line.find("//") != 0)
    {
        size_t pos = line.find("|");
        if (pos != std::string::npos)
        {
            key = line.substr(0, pos);
             size_t pos1 = line.find(";");
            value = line.substr(pos + 1, pos1);
            flag = true;
        }
    }
    return flag;
}

两个问题在提取大学值时,我在第一年得到诸如"USA|"之类的所有东西,但我只想要美国和名称逻辑不起作用

请指导

我会尝试逐字阅读流,并检查适当的名称和大学:

int main()
{
    std::ifstream ifs("Ca.txt");
    std::string line, word;
    Demo obj;
    while (std::getline(ifs, line))
    {
        std::istringstream iss(line);
        while (iss >> word)
        {
            if ((word == "student") && iss >> word)
            {
                obj.data.name = word;
            } else if (word.find("university") != std::string::npos)
            {
                size_t pos1 = word.find_first_of("|"),
                       pos2 = word.find_last_of("|");
                obj.data.university = word.substr(pos1 + 1, pos2 - pos1 - 1);
            }
        }
        std::cout << "Name: "       << obj.data.name << "n"
                  << "University: " << obj.data.university << std::endl;
    }
}