2011-04-20 29 views
0

我可以請一些指導來構建一個輸入文件的解析器,我一直在尋找幫助幾個星期,任務已經過期,我只想知道如何去做。如何構建輸入文件的解析器

評論的代碼是我嘗試過的,但我覺得它比這更嚴重。我有一個文本文件,我想解析它來計算單詞出現在文檔中的次數。

Parser::Parser(string filename) { 
    //ifstream.open(filename); 

    // source (filename, fstream::in | fstream::out); 

} 
+1

**龍書**真實的一句話:http://en.wikipedia.org/ wiki/Compilers:_Principles,_Techniques,_and_Tools – 2011-04-20 19:53:08

+0

您可能需要告訴我們關於輸入文件的格式,然後才能給出任何真正的智能建議。 – 2011-04-20 19:54:51

+1

@Nikolai N Fetissov:我認爲一本關於C++的書會更合適。 – orlp 2011-04-20 19:55:38

回答

0

要讀一個字:

std::ifstream file("FileName"); 

std::string word; 
file >> word; // reads one word from a file. 


// Testing a word: 
if (word == "Floccinaucinihilipilification") 
{ 
    ++count; 
} 

// Count multiple words 
std::map<std::string, int> count; 

// read a word 
++count[word]; 

// To read many words from a file: 

std::string word; 
while(file >> word) 
{ 
    // You have now read a word from a file 
} 

注:這是:-)
http://dictionary.reference.com/browse/floccinaucinihilipilification

+0

您是否從YouTube上的hotforwords瞭解到這一點? – 2011-04-20 20:04:38

+0

那麼我如何讓解析器讀取整個文件而不是一個字? – Technupe 2011-04-20 20:10:18

+0

請參閱http://stackoverflow.com/questions/625247/how-do-you-read-a-word-in-from-a-file-in-c閱讀整個文件。 – evnu 2011-04-20 20:43:54

1

註釋的代碼是什麼我已經試過,但我有一種感覺,它是比這更嚴重。

我有一種感覺,你還沒有嘗試過的東西。所以我也會這樣做。

Google is your friend

0

看看How do you read a word in from a file in C++?的答案。最簡單的方法是使用ifstreamoperator>>來讀取單個單詞。然後,您可以使用標準容器,如vector(如上面鏈接中提到的)或map<string, int>來記住實際計數。