#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" を生成します。
また、ファイルを閉じてから、しばらくの間ファイルを再度開く必要はありません。最後のwhileループからまだファイルの最後にあるようです。