c++ - 我如何制作 C++ 医院管理程序的这个(逻辑)部分?
问题描述
我正在寻求帮助以了解此处必须使用什么逻辑。
我必须向用户显示一些城市的名称。然后用户可以选择一个城市。从所选城市中,必须显示属于该城市的特定医生的姓名,用户可以从中选择医生。
我试图制作一个txt文件,并将数据导入程序。但是这样一来,就不能先输出城市名,然后再从那个城市选择医生。
我也尝试使用结构,但同样的问题,因为我无法先打印城市名称,然后再打印该城市的医生。
解决方案
你还不清楚你的文本文件是什么样的,所以我假设它是逗号分隔的,并且包含两列:city,doctor
我们不想从文件中读取逗号分隔的项目,因为如果一行只有一个城市或一个医生,但不是两者,我们将忘记我们正在阅读哪个。因此,我们应该从文件中读取整行,然后将它们分成城市和医生。这样我们就可以忽略没有城市和医生的线路。
然后你必须阅读文件。如果您使用的地图使用城市作为键,医生向量作为值,那么您可以在知道城市后枚举键或枚举其中一个向量:std::map<std::string,std::vector<std::string> > city_doctor_map;
这是一个包含输入文件的工作示例的链接:https ://onlinegdb.com/H1N0gFTZr
这是我想出的代码:
#include <map>
#include <vector>
#include <sstream>
#include <fstream>
#include <iostream>
int main()
{
// first open the file
std::ifstream fin("untitled.txt");
// then read lines from the file
std::string str;
std::map<std::string,std::vector<std::string> > city_doctor_map;
while(getline(fin,str))
{
// and for each line put it in a string stream so we can split it up afterwards
std::stringstream ss;
ss << str;
// we could just read comma separated bits directly from the file with
// while(getline(fin,str,',')) { ... }
// but then if one of the lines doesn't have both halves we get messed up
// so it is better if we read one line at a time and split that up afterward
// then read comma separated bits from the string stream
std::string city,doctor;
if(getline(ss,city,',') && getline(ss,doctor,','))
{
// if we don't have both bits then don't do anything
if (city.length()>0 && doctor.length()>0)
{
// if we do have both bits then get the vector of doctors from the map
// (creating it if necessary) and add the doctor to it
std::vector<std::string> &doctors = city_doctor_map[city];
doctors.push_back(doctor);
std::cout << "added " << doctor << " to " << city << "\n";
}
}
}
// now print the keys of the map
std::cout << "\ncities:\n";
for ( const auto &item : city_doctor_map ) {
std::cout << item.first << "\n";
}
// you could read this from the user input...
std::string city = "city4";
// now print the doctors in the city
std::cout << "\ndoctors in " << city << ":\n";
for ( const auto &item : city_doctor_map[city] ) {
std::cout << item << "\n";
}
// all done
return 0;
}
推荐阅读
- sql - SQL 调优顾问中的绑定日期
- python - python中的函数如何维护状态?
- perforce - 由于孤立的更改列表,无法删除用户
- php - 从引导数据表中的 2 个站点请求数据
- asp.net-mvc - ASP.Net MVC 控制器的数据注释是否有顺序
- java - 斯坦福 CoreNLP - 无法正确识别引理
- sql - Oracle 从值包含下划线的表中选择
- sql - 如何使用窗口函数枚举 Postgres 表中的分区组?
- alamofire - Alamofire + Decodable - 如何将 responseJSON 转换为 NSData
- qt - 防止 QtWebEngine 重定向到特定域