使用map计算每个单词在文件中出现的次数.(c++)

Counting how many times each word occurs in a file using map. (c++)

本文关键字:c++ 计算 map 单词 文件 使用      更新时间:2023-10-16
#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 << "nn" << "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循环的文件末尾

您需要遍历映射,而不是第二次打开文件。

查看这里提供的代码示例。

编辑:这里是一个通过映射迭代的代码示例

// 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

你不需要重新打开文件:

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;
}

您需要在设置后遍历地图,然后您不需要再次打开文件,这是一个微不足道的示例:

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