2012-04-19 55 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雖然你可能不關心它。