#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <map>
using namespace std;
int main()
{
ifstream fin;
fin.open("myTextFile.txt");
if (fin.fail()){
cout << "Could not open input file.";
exit(1);
}
string next;
map <string, int> words;
while (fin >> next){
words[next]++;
}
cout << "\n\n" << "Number of words: " << words[next] << endl;
fin.close();
fin.open("myTextFile.txt");
while (fin >> next){
cout << next << ": " << words[next] << endl;
}
fin.close();
return 0;
}
我的主要問題是,當一個單詞出現不止一次時,它也會多出現一次。即如果文本以「hello hello」開頭,那麼cout產生: 「hello:2」'n'「hello:2」使用映射計算每個單詞在文件中出現的次數。 (C++)
另外,我想不必關閉,然後重新打開文件第二次是真實的。它看起來仍然在最後while循環的文件末尾。
你的單詞數量只會打印最後一個單詞的數量。另外,遍歷地圖,不要再次讀取文件(假設你改了名字,忘記改變另一個,根據你說的重新打開來判斷)。 – chris 2013-03-18 15:22:39