用C++代码写一个火车票管理系统
时间: 2023-11-08 19:05:43 浏览: 17
好的,以下是一个简单的火车票管理系统的C++代码,包含了添加、查询和删除功能:
```cpp
#include<iostream>
#include<fstream>
#include<string>
#include<cstdlib>
using namespace std;
class Train {
public:
string train_number;
string departure_time;
string arrival_time;
string start_station;
string end_station;
int seat_number;
int price;
void add_train() {
cout << "Please input the train number: ";
cin >> train_number;
cout << "Please input the departure time: ";
cin >> departure_time;
cout << "Please input the arrival time: ";
cin >> arrival_time;
cout << "Please input the start station: ";
cin >> start_station;
cout << "Please input the end station: ";
cin >> end_station;
cout << "Please input the seat number: ";
cin >> seat_number;
cout << "Please input the price: ";
cin >> price;
ofstream fout("train.txt", ios::app);
fout << train_number << " " << departure_time << " " << arrival_time << " " << start_station << " " << end_station << " " << seat_number << " " << price << endl;
fout.close();
cout << "Train added successfully!" << endl;
}
void query_train() {
cout << "Please input the train number: ";
string number;
cin >> number;
ifstream fin("train.txt");
string train_info;
bool flag = false;
while (getline(fin, train_info)) {
if (train_info.find(number) != string::npos) {
cout << train_info << endl;
flag = true;
}
}
fin.close();
if (!flag) {
cout << "Train not found!" << endl;
}
}
void delete_train() {
cout << "Please input the train number: ";
string number;
cin >> number;
ifstream fin("train.txt");
ofstream fout("tmp.txt");
string train_info;
bool flag = false;
while (getline(fin, train_info)) {
if (train_info.find(number) != string::npos) {
flag = true;
}
else {
fout << train_info << endl;
}
}
fin.close();
fout.close();
if (flag) {
remove("train.txt");
rename("tmp.txt", "train.txt");
cout << "Train deleted successfully!" << endl;
}
else {
cout << "Train not found!" << endl;
remove("tmp.txt");
}
}
};
int main() {
Train train;
while (true) {
cout << "Please select an option:" << endl;
cout << "1. Add train" << endl;
cout << "2. Query train" << endl;
cout << "3. Delete train" << endl;
cout << "4. Exit" << endl;
int option;
cin >> option;
switch (option) {
case 1:
train.add_train();
break;
case 2:
train.query_train();
break;
case 3:
train.delete_train();
break;
case 4:
exit(0);
break;
default:
cout << "Invalid option, please try again!" << endl;
break;
}
}
return 0;
}
```
注意:这只是一个简单的示例,实际情况中需要更完善的功能和异常处理。