【问题标题】:Counting how many times each word occurs in a file using map. (c++)使用 map 计算每个单词在文件中出现的次数。 (c++)
【发布时间】: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 循环的文件末尾。

【问题讨论】:

  • 您的字数只会打印最后一个字的计数。另外,遍历地图,不要再次读取文件(假设您更改了名称并忘记更改另一个名称,根据您所说的重新打开来判断)。

标签: c++ string file-io map


【解决方案1】:

您需要遍历地图,而不是再次打开文件。

查看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

【讨论】:

    【解决方案2】:

    你不需要重新打开文件:

    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,还不如用ranged-based for呢!
    【解决方案3】:

    你需要在设置后遍历地图,然后你不需要再次打开文件,这是一个简单的例子:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-05
      • 2018-08-25
      • 1970-01-01
      相关资源
      最近更新 更多