使用映射计算每个单词在文件中出现的次数。 (C++)
#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循环的文件末尾。
您需要迭代通过地图,而不是第二次打开文件。
看看提供的代码示例here。
编辑:下面一个代码示例,迭代低谷地图
// map::begin/end
#include <iostream>
#include <map>
int main()
{
std::map<char,int> mymap;
std::map<char,int>::iterator it;
mymap['b'] = 100;
mymap['a'] = 200;
mymap['c'] = 300;
// show content:
for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
std::cout << it->first << " => " << it->second << '\n';
return 0;
}
这里是输出:
a => 200
b => 100
c => 300
你也可以在你的答案中提供正确的代码吗? – Pubby 2013-03-18 15:24:40
您不必再打开文件:
for (auto i = words.begin(); i != words.end(); i++)
{
cout << i->first << " : " << i->second << endl;
}
或更简单:
for (const auto &i : words)
{
cout << i.first << " : " << i.second << endl;
}
如果你使用的是C++ 11,那么也可以使用基于范围的! – Pubby 2013-03-18 15:30:27
你需要你设置它,那么你就不需要再次打开该文件后,迭代在地图上,这是简单的例子:
int main()
{
std::map<std::string, int> m1 ;
m1["hello"] = 2 ;
m1["world"] = 4 ;
for(const auto &entry : m1)
{
std::cout << entry.first << " : " << entry.second << std::endl ;
}
}
预期输出是:
hello : 2
world : 4
你的单词数量只会打印最后一个单词的数量。另外,遍历地图,不要再次读取文件(假设你改了名字,忘记改变另一个,根据你说的重新打开来判断)。 – chris 2013-03-18 15:22:39