首页 > 解决方案 > 从 C++ 中的文本文件中读取

问题描述

我想寻求帮助以完成我的 C++ 项目。问题是关于从包含 18 个名字的故事的文本文件中读取。这些名字在故事中重复了很多次。该程序应计算重复的名称。

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
    ifstream in("Romeo and Juliet.txt");
    ofstream out;

    string name[] = {"Escalus","Paris","Montague","Capulet","Romeo","Tybalt",
                     "Mercutio","Benvolio","Friar Laurence","Friar 
                      John","Balthasar","Abram","Sampson","Gregory",
                      "Peter","Lady Montague","Lady Capulet","Juliet"};
    string str;
    int scount=0,v[18];

    for(int i=0;i<18;i++)
    {
     scount=0;
        while(!in.eof())
       {

           while(getline(in,str))
           {
               if(str==name[i])
               {
                   scount++;
               }
           }
       }
        v[i]=scount;
    }

      for(int i=0;i<18;i++)
      {
         cout<<v[i]<<endl;
      }
       in.close();
 }

标签: c++

解决方案


如果你使用std::string我认为你可以使用std::map.

地图用于计算文本中的名称。

map < string, int > v;
for (int i = 0; i < 18; i++)
    v[name[i]] = 0;

对于逐字输入,我使用:

freopen("Romeo and Juliet.txt", "r", stdin);
while (cin >> str)
{
    if (str == "Friar" || str == "Lady")
    {
        string s;
        cin >> s;
        if (s.empty())
            continue;
        if ( ((s == "Montague" || s == "Capulet") && str == "Lady") ||
            str == "Friar" && s == "Laurence")
        {
            v[str + " " + s]++;
        }
        else if (v.find(s) != v.end())
            v[s]++;

    }
    else if (v.find(str) != v.end())
        v[str]++;
}    

地图的输出值:

for (auto it = v.begin(); it != v.end(); it++)
{
    cout << it->first << " " << it->second << endl; 
}

这是有效的。


推荐阅读