我有一个像这样的文件
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 |”这样的东西。在第一年“但我只想要美国和名字逻辑不工作
请指导
答案 0 :(得分:0)
我会尝试逐字地阅读流,并检查适当的名称和大学:
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;
}
}