我可以請一些指導來構建一個輸入文件的解析器,我一直在尋找幫助幾個星期,任務已經過期,我只想知道如何去做。如何構建輸入文件的解析器
評論的代碼是我嘗試過的,但我覺得它比這更嚴重。我有一個文本文件,我想解析它來計算單詞出現在文檔中的次數。
Parser::Parser(string filename) {
//ifstream.open(filename);
// source (filename, fstream::in | fstream::out);
}
我可以請一些指導來構建一個輸入文件的解析器,我一直在尋找幫助幾個星期,任務已經過期,我只想知道如何去做。如何構建輸入文件的解析器
評論的代碼是我嘗試過的,但我覺得它比這更嚴重。我有一個文本文件,我想解析它來計算單詞出現在文檔中的次數。
Parser::Parser(string filename) {
//ifstream.open(filename);
// source (filename, fstream::in | fstream::out);
}
要讀一個字:
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
看看How do you read a word in from a file in C++?的答案。最簡單的方法是使用ifstream
和operator>>
來讀取單個單詞。然後,您可以使用標準容器,如vector
(如上面鏈接中提到的)或map<string, int>
來記住實際計數。
**龍書**真實的一句話:http://en.wikipedia.org/ wiki/Compilers:_Principles,_Techniques,_and_Tools – 2011-04-20 19:53:08
您可能需要告訴我們關於輸入文件的格式,然後才能給出任何真正的智能建議。 – 2011-04-20 19:54:51
@Nikolai N Fetissov:我認爲一本關於C++的書會更合適。 – orlp 2011-04-20 19:55:38