C++ 使用map计算每个单词在文件中出现的次数。(c+;+;) #包括 #包括 #包括 #包括 #包括 使用名称空间std; int main() { 流鳍; 打开(“myTextFile.txt”); if(fin.fail()){ cout>下一步){ 单词[下一个]+; } cout

C++ 使用map计算每个单词在文件中出现的次数。(c+;+;) #包括 #包括 #包括 #包括 #包括 使用名称空间std; int main() { 流鳍; 打开(“myTextFile.txt”); if(fin.fail()){ cout>下一步){ 单词[下一个]+; } cout,c++,string,file-io,map,C++,String,File Io,Map,您需要通过映射进行迭代,而不是再次打开文件 请看提供的代码示例 编辑:这里是一个通过映射进行迭代的代码示例 #include <iostream> #include <fstream> #include <cstdlib> #include <string> #include <map> using namespace std; int main() { ifstream fin; fin.open("myTextF

您需要通过映射进行迭代,而不是再次打开文件

请看提供的代码示例

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

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

您需要通过映射进行迭代,而不是再次打开该文件

请看提供的代码示例

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

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

您不需要重新打开文件:

a => 200
b => 100
c => 300
for(自动i=words.begin();i!=words.end();i++)
{

不能首先您不需要重新打开文件:

a => 200
b => 100
c => 300
for(自动i=words.begin();i!=words.end();i++)
{

cout首先您需要在设置映射后对其进行迭代,然后无需再次打开该文件,这是一个简单的示例:

for (const auto &i : words)
{
  cout << i.first << " : " << i.second << endl;
}

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

for (const auto &i : words)
{
  cout << i.first << " : " << i.second << endl;
}

您的字数将只打印最后一个单词的计数。此外,在地图中迭代,不要再次读取该文件(假设您更改了名称,但忘记更改了另一个名称,这取决于您如何说“重新打开”)。您的字数将只打印最后一个单词的计数。此外,在地图中迭代,不要再次读取该文件(假设您更改了名称,但忘了更改另一个名称,这取决于您如何说“重新打开”)。如果您使用C++11,也可以使用基于范围的!如果您使用C++11,也可以使用基于范围的!
hello : 2
world : 4