c++ - 从 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();
}
解决方案
如果你使用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;
}
这是有效的。
推荐阅读
- javascript - Vue.js。TypeError:即使确实安装了 vue-resource,也无法读取未定义的属性“帖子”
- https - 在 Alpine linux 中向仅 TLS1.0 的服务器发送 HTTPS 请求
- c - 是否可以像普通数组一样获得函数指针数组的大小?
- java - 在一个 lambda 表达式中收集复杂对象
- java - 在 Spring Boot 和 ElasticSearch 中使用 Instant、LocalDateTime 和 ZonedDateTime
- webpack - webpack-dev-server 端口自动分配
- entity-framework-core - 引入 FOREIGN KEY 约束 - 基本迁移
- c# - 未找到 Elasticsearch NEST Suggester 解析器
- sql - 获取帐户的查询与日期范围不冲突
- android - 为什么我会看到 Android 模拟器应用程序运行错误?