我有作业。我必须创建一个哈希表并使用链表来解决冲突。哈希表工作得很好。作业的一部分是读取文件并解析内容以获取指令。
文件内容:
Load("Via Lactea", "Galaxia")
Load("Galaxia", "Sistema Solar", "Sol")
Load("Via Lactea", "Hoyo negro", "001")
Find("Via Lactea","Luna")
Delete("Via Lactea","Jupiter")
Show()
我的问题是什么是创建 C/C++ 程序以读取文件内容并解析指令以运行我的程序的最佳(和最简单)方法。我是 C/C++ 的新手,所以我不确定解决这个问题的最佳方法是什么。
如何看一行就知道是什么指令?
我想知道一些想法
(我的哈希表代码在这里 http://pastebin.com/yVEeqvzG )
最佳答案
由于您的作业的主要目标是哈希表部分,您可能想要进行一个快速而肮脏的 hack 来解析您的文件,这样您就可以快速开始主要部分。
以下是用 C 编写的,但它也会在 C++ 中运行。
char line[100], command[100], word1[100], word2[100], word3[100];
FILE* f = fopen("whatever", "rt");
while (fgets(line, sizeof(line), f)) // read one line of text from file
{
// The following is a format string for scanf.
// It matches an opening quote, some text, and a closing quote.
#define WORD "\"%[^\"]\""
// Try to parse the line of text, applying all possible patterns.
if (sscanf(line, "Load("WORD", "WORD", "WORD")\n", word1, word2, word3) == 3)
{
...
}
else if (sscanf(line, "Load("WORD", "WORD")\n", word1, word2) == 2)
{
...
}
else if (sscanf(line, "Find("WORD", "WORD")\n", word1, word2) == 2)
{
...
}
else if (strcmp(line, "Show()\n") == 0)
{
...
}
}
必读:sscanf
的用法has security holes尽管您可能不关心它。
关于c++ - 从文本文件中获取指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10235682/