我有以下课程
class Film {
Person authors[5]; //This will actually include only the director
string title;
string producer;
int n_authors;
int year;
int running_time;
Person actors[5];
int n_actors;
}
Run Code Online (Sandbox Code Playgroud)
以下文件格式(不要问我为什么使用这个,我必须使用这种格式)
Stanley
Kubrick
#
2001: A Space Odissey
*
1968
161
Keir
Dullea
Gary
Lockwood
#
Run Code Online (Sandbox Code Playgroud)
该#指示表(在这种情况下,"人"类)的结束,而*缺少场(在这种情况下,生产商,者均基于producer字段必须填充*的类).该类Person包含Name和Surname重载operator >>调用:
void load(ifstream& in) {
getline(in,name);
getline(in,surname);
}
Run Code Online (Sandbox Code Playgroud)
解析此文件结构的最佳方法是什么?我不能使用正则表达式或比ifstream更高级的东西.我关注的是如何(以及在代码中的哪个位置)检测文件结尾和人员列表的结尾.
非常感谢您的帮助!(如果你能用英语纠正任何错误,我会很高兴!:))
标准读书成语:
#include <fstream> // for std::ifstream
#include <sstream> // for std::istringstream
#include <string> // for std::string and std::getline
int main()
{
std::ifstream infile("thefile.txt");
std::string line;
while (std::getline(infile, line))
{
// process line
}
}
Run Code Online (Sandbox Code Playgroud)
如果它说"过程线",你应该添加一些跟踪解析器当前状态的逻辑.
对于您的简单应用程序,您可以按照格式指定的位,读取列表和标记进行操作.例如:
std::vector<std::string> read_list(std::istream & in)
{
std::string line;
std::vector<std::string> result;
while (std::getline(in, line))
{
if (line == "#") { return result; }
result.push_back(std::move(line));
}
throw std::runtime_error("Unterminated list");
}
Run Code Online (Sandbox Code Playgroud)
现在你可以说:
std::string title, producer, token3, token4, token5, token6;
std::vector<std::string> authors = read_list(infile);
if (!(std::getline(infile, title) &&
std::getline(infile, producer) &&
std::getline(infile, token3) &&
std::getline(infile, token4) &&
std::getline(infile, token5) ) )
{
throw std::runtime_error("Invalid file format");
}
std::vector<std::string> actors = read_list(infile);
Run Code Online (Sandbox Code Playgroud)
您可以使用std::stoi将标记3 - 5转换为整数:
int year = std::stoi(token4);
int runtime = std::stoi(token5);
Run Code Online (Sandbox Code Playgroud)
请注意,n_authors和n_actors变量是多余的,因为您已经有自终止列表.如果您愿意,您可以或应该使用变量作为完整性检查.