用C++代码写一个火车票管理系统
时间: 2023-11-06 19:04:01 浏览: 55
基于C++的火车票管理系统
5星 · 资源好评率100%
以下是一个简单的火车票管理系统的 C++ 代码,实现了添加、删除、查询和展示火车票信息的功能。
```
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// 火车票信息结构体
struct Ticket {
string trainNumber; // 车次
string startStation; // 起始站
string endStation; // 终点站
string departureTime; // 出发时间
string arrivalTime; // 到达时间
int price; // 票价
};
// 火车票管理系统类
class TicketSystem {
private:
vector<Ticket> tickets; // 火车票信息容器
public:
// 添加一张火车票
void addTicket(const Ticket& ticket) {
tickets.push_back(ticket);
cout << "添加火车票成功!" << endl;
}
// 删除一张火车票
void deleteTicket(const string& trainNumber) {
for (auto it = tickets.begin(); it != tickets.end(); ++it) {
if (it->trainNumber == trainNumber) {
tickets.erase(it);
cout << "删除火车票成功!" << endl;
return;
}
}
cout << "没有找到该车次的火车票。" << endl;
}
// 查询一张火车票
void queryTicket(const string& trainNumber) {
for (auto it = tickets.begin(); it != tickets.end(); ++it) {
if (it->trainNumber == trainNumber) {
cout << "车次:" << it->trainNumber << endl;
cout << "起始站:" << it->startStation << endl;
cout << "终点站:" << it->endStation << endl;
cout << "出发时间:" << it->departureTime << endl;
cout << "到达时间:" << it->arrivalTime << endl;
cout << "票价:" << it->price << endl;
return;
}
}
cout << "没有找到该车次的火车票。" << endl;
}
// 显示所有火车票信息
void showAllTickets() {
for (auto it = tickets.begin(); it != tickets.end(); ++it) {
cout << "车次:" << it->trainNumber << endl;
cout << "起始站:" << it->startStation << endl;
cout << "终点站:" << it->endStation << endl;
cout << "出发时间:" << it->departureTime << endl;
cout << "到达时间:" << it->arrivalTime << endl;
cout << "票价:" << it->price << endl;
cout << endl;
}
}
};
int main() {
TicketSystem ts;
int choice;
string trainNumber;
Ticket ticket;
while (true) {
cout << "请选择操作:" << endl;
cout << "1. 添加一张火车票" << endl;
cout << "2. 删除一张火车票" << endl;
cout << "3. 查询一张火车票" << endl;
cout << "4. 显示所有火车票信息" << endl;
cout << "5. 退出系统" << endl;
cin >> choice;
switch (choice) {
case 1:
cout << "请输入车次:" << endl;
cin >> ticket.trainNumber;
cout << "请输入起始站:" << endl;
cin >> ticket.startStation;
cout << "请输入终点站:" << endl;
cin >> ticket.endStation;
cout << "请输入出发时间:" << endl;
cin >> ticket.departureTime;
cout << "请输入到达时间:" << endl;
cin >> ticket.arrivalTime;
cout << "请输入票价:" << endl;
cin >> ticket.price;
ts.addTicket(ticket);
break;
case 2:
cout << "请输入要删除的火车票的车次:" << endl;
cin >> trainNumber;
ts.deleteTicket(trainNumber);
break;
case 3:
cout << "请输入要查询的火车票的车次:" << endl;
cin >> trainNumber;
ts.queryTicket(trainNumber);
break;
case 4:
ts.showAllTickets();
break;
case 5:
cout << "感谢使用火车票管理系统,再见!" << endl;
return 0;
default:
cout << "无效的操作,请重新选择。" << endl;
break;
}
}
}
```
阅读全文