0
#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”

另外,我不想关闭,然后第二次重新打开文件。似乎它仍然在最后一个 while 循环的文件末尾。

4

3 回答 3

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;
}
于 2013-03-18T15:25:47.943 回答
2

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

查看此处提供的代码示例。

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

// 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
于 2013-03-18T15:24:03.510 回答
0

您需要在设置地图后对其进行迭代,然后您不需要再次打开文件,这是一个简单的示例:

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
于 2013-03-18T15:26:33.227 回答