我想用c++实现一个交通咨询系统,数据项包括起始站城市的名称,终点站名称,两个城市间的距离,时间,价钱,能够实现添加两个城市间的信息,且能查询两个城市间的最短距离并将输入的两个城市间的信息写入到文本文件中
时间: 2024-05-14 10:12:43 浏览: 85
数据结构课设基于C++的交通咨询系统源码+实验报告+代码注释.zip
以下是一个简单的交通咨询系统的C语言实现,包括添加信息、查询最短距离和将信息写入文本文件:
```
#include <stdio.h>
#include <string.h>
#define MAX_CITY_NAME 50
#define MAX_NUM_CITIES 100
typedef struct {
char name[MAX_CITY_NAME];
} City;
typedef struct {
int distance;
int time;
int price;
} Route;
typedef struct {
City start_city;
City end_city;
Route route;
} CityRoute;
CityRoute city_routes[MAX_NUM_CITIES];
int num_city_routes = 0;
// Adds a route between two cities
void add_route(City start_city, City end_city, Route route) {
CityRoute city_route = {start_city, end_city, route};
city_routes[num_city_routes++] = city_route;
}
// Finds the shortest distance between two cities
int find_shortest_distance(City start_city, City end_city) {
int shortest_distance = -1;
for (int i = 0; i < num_city_routes; i++) {
CityRoute city_route = city_routes[i];
if (strcmp(city_route.start_city.name, start_city.name) == 0 &&
strcmp(city_route.end_city.name, end_city.name) == 0) {
if (shortest_distance == -1 || city_route.route.distance < shortest_distance) {
shortest_distance = city_route.route.distance;
}
}
}
return shortest_distance;
}
// Writes city route information to a text file
void write_city_routes_to_file(char* filename) {
FILE* fp = fopen(filename, "w");
if (fp == NULL) {
printf("Error opening file %s\n", filename);
return;
}
for (int i = 0; i < num_city_routes; i++) {
CityRoute city_route = city_routes[i];
fprintf(fp, "%s,%s,%d,%d,%d\n", city_route.start_city.name, city_route.end_city.name,
city_route.route.distance, city_route.route.time, city_route.route.price);
}
fclose(fp);
}
int main() {
// Add some example city routes
City beijing = {"Beijing"};
City shanghai = {"Shanghai"};
City guangzhou = {"Guangzhou"};
Route beijing_shanghai = {1064, 120, 500};
Route shanghai_guangzhou = {1782, 240, 800};
Route beijing_guangzhou = {1888, 180, 1000};
add_route(beijing, shanghai, beijing_shanghai);
add_route(shanghai, guangzhou, shanghai_guangzhou);
add_route(beijing, guangzhou, beijing_guangzhou);
// Find the shortest distance between Beijing and Guangzhou
int shortest_distance = find_shortest_distance(beijing, guangzhou);
printf("Shortest distance between Beijing and Guangzhou: %d km\n", shortest_distance);
// Write city route information to a text file
write_city_routes_to_file("city_routes.txt");
return 0;
}
```
在这个实现中,我们定义了三个结构体类型:City表示城市,Route表示两个城市之间的距离、时间和价格,CityRoute表示两个城市之间的路线,包括起始城市、终点城市和路线信息。
我们使用一个数组来存储所有的CityRoute,通过add_route函数向数组中添加新的路线信息。find_shortest_distance函数用于查找两个城市之间的最短距离,它遍历所有的CityRoute,找到起始城市和终点城市都匹配的那个路线,并比较路线的距离来确定最短距离。write_city_routes_to_file函数用于将所有的CityRoute信息写入到文件中,它打开指定的文本文件,遍历所有的CityRoute,将信息写入文件中,并关闭文件。
在main函数中,我们添加了一些示例路线信息,并调用find_shortest_distance和write_city_routes_to_file函数。最后,程序返回0表示执行成功。
阅读全文