【发布时间】:2013-03-18 15:20:38
【问题描述】:
#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 会产生: "你好:2" '\n' "你好:2"
另外,我希望不必关闭文件,然后再重新打开文件。似乎它仍然在最后一个 while 循环的文件末尾。
【问题讨论】:
-
您的字数只会打印最后一个字的计数。另外,遍历地图,不要再次读取文件(假设您更改了名称并忘记更改另一个名称,根据您所说的重新打开来判断)。