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

标签 c++ string file-io dictionary

#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 循环的文件末尾。

最佳答案

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

查看提供的代码示例 here .

编辑:这里是一个遍历 map 的代码示例

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

关于c++ - 使用 map 计算每个单词在文件中出现的次数。 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15480357/

相关文章:

c++ - 如何实现decltype功能-C++ 11之前的编译时间

javascript - 用于替换标点符号(不包括负数)的正则表达式

c - 如何用C语言在文件的特定位置写入字符串

c# - C++/CLI 项目如何引用可移植类库?

c++ - OpenGL 3/GLFW 空白视口(viewport)

iphone - 如何在 Objective-C 中将字符串转换为数组?

python - 文件打开/阅读语言的速度是否取决于语言?

java - JFileChooser:保存取消之前用户导航到的最后一个目录

c++ - 我可以在 qt Creator 中使用带有 try catch 语句的断点吗?

c++ - C++中的字符串对象