2012-04-19 57 views
0

我有作业。我必须创建一个哈希表并使用链表来解决割集。哈希表工作得很好。部分排序是读取文件并解析内容以获得指示。从文本文件获取说明

文件内容:

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

+3

哪种语言? C还是C++? – 2012-04-19 19:49:52

+0

什么。不知道他们之间有什么区别,除了类的东西 – chepe263 2012-04-19 19:50:34

+0

当然,你打算使用其中一个。 – 2012-04-19 19:51:33

回答

0

这个基本片段是能够通过线加载文件行。如何管理解析是你的责任,我会去与strtok_s,但你将不得不关心修剪空间,检查适量的参数,从字符串和其他任何提取双引号。

#include <iostream> 
#include <fstream> 
using namespace std; 

int main() { 
    filebuf fb; 
    fb.open("data.txt",ios::in); 
    istream is(&fb); 
    char buffer[256]; 

    while ((is.rdstate() & ifstream::eofbit) == 0) { 
    is.getline(buffer,256); 

    // handle your parsing here 
    } 

    fb.close(); 
    return 0; 
} 
+1

strtok是EVIL,请勿触摸:) – ScarletAmaranth 2012-04-19 20:17:05

+0

忘记指定'strtok_s',现在正在编辑:P – Jack 2012-04-19 20:19:14

+0

上次我使用常规strtok我的编译器骂我像个小孩:) – ScarletAmaranth 2012-04-19 20:21:46

1

因为你的任务的主要目标是Hashtable的一部分,你可能要做出一个快速和肮脏的黑客,它分析你的文件,只是让你可以迅速与主要部分开始。

以下是用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) 
    { 
     ... 
    } 
} 

强制性注:这种用法的sscanfhas security holes虽然你可能不关心它。