文件解析代码需要注意
File parsing code need attention
我有这样的文件
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;
}
}
相关文章:
- 在C++代码中包含opencv时,使用ctypes创建.so文件
- 此代码编译良好,但文件未创建?请指出错误
- 找不到Linux Visual Studio代码C++文件
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- Visual Studio代码文件未输出
- 是否可以使用 GCC 编译具有特定编译器标志的代码文件的一部分?
- 如何从ifstream加载LLVM比特代码文件
- 在同一代码文件中包括 Directx 9 和 10
- 如果我只想要架构良好的工作区,但不一定是分开的编译,如何在C++中组织头/代码文件
- 使用 Eclipse 运行.exe C 代码文件
- 是否可以稍后在代码(C++ I/O 文件)中使用输出文件作为输入文件
- 匿名命名空间-在头文件和代码文件中都有意义
- 代码文件外的代码文档
- 在静态库中硬编码的代码文件和头路径
- 更快地解析代码文件
- 为什么有些代码文件使用 close() 而不包含 unistd.h
- 在代码(.c文件)我如何找到linux发行版名称版本
- 在一个代码文件中使用头文件,反之亦然
- SonarQube未分析带有警告的C++代码文件不在项目目录下
- Qt 创建器代码文件重构