(1) Ниже приведен обновленный код, поскольку у вашего кода было несколько проблем.Я уверен, что, глядя на приведенный ниже код, вы сможете понять ошибки в вашем коде.Не стесняйтесь использовать это как основу для написания своей собственной версии.(2) Пожалуйста, внимательно прочитайте встроенные комментарии.Комментарии подробно объясняют цель этого раздела кода (3). Это всего лишь быстрый код.Я не скомпилировал / запустил / протестировал этот код.Мое намерение состоит в том, чтобы просто дать вам представление об этом на одном возможном примере.
/ * Очень простой модуль менеджера парковки
Когда автомобиль входит для парковки a) захватить информацию об автомобиле и парковкуномер партии, где находится парковка b) отметить этот участок как недоступный
Когда транспортное средство покидает парковку, запишите номер стоянки, который очищается, и пометьте этот участок как доступный
И,повеселиться на пути.* /
#include<stdio.h>
#define YOU_ARE_TRAPPED_BY_THE_BIG_BAD_GREEN_SCARY_MONSTER ({printf("HA HA HA, You didn't read and follow the inline comments !!\nNow stand up, jump 3 times, then sit down, and read all the comments again and do the min code modif to make me go away, else i won't let you escape the parking lot ... hoo ha ha ha ha >-)\n"); updateVehicleParkingInfo=1;})
#include<stdlib.h>
struct Vehichle{
char vecType[100]; //type of vehicle eg suv,mpv and more...
char plateNo[10]; //number plate of the vehicle
float hours; //???
};
struct Parking{
int parkNo ; //parking lot num
bool availability; //Is tbis parking space available? Yes/No
};
struct VehicleParkingInfo{
struct Vehicle vehicle; //vehicle info
struct Parking parking; //corresponding parking info
};
//maximum number of parking lots that the parking space has
#define MAX_PARKING_LOTS 10
//parking lot avaialble flags
#define PARKING_LOT_AVAILABLE true
#define PARKING_LOT_UNAVAILABLE false
//flags for vehicle coming in or leaving
#define VEHICLE_ENTERING true
#define VEHICLE_LEAVING false
void main(){
int updateVehicleParkingInfo; //flag indicating that user wants to update parking info.
int vehicleDirection; //flag for indicating whether the vehicle is coming in or going out of the parking
int parkingIdx; //index of the parking lot to fetch values from.
//array for info about all the parking lots
struct VehicleParkingInfo vehicleParkingInfo[MAX_PARKING_LOTS];
//initialize the parking & vehicle info of all the parking lots to zeros
memset(vehicleParkingInfo,0,MAX_PARKING_LOTS*sizeof(VehicleParkingInfo));
//for each parking lot, mark it as available and assign parking lot numbers serially
for(parkingIdx = 0; parkingIdx < MAX_PARKING_LOTS; parkingIdx++){
vehicleParkingInfo[parkingIdx].parking.parkNo = parkingIdx;
vehicleParkingInfo[parkingIdx].parking.availability = PARKING_LOT_AVAILABLE;
}
//get user's input if parking info needs to be updated or it is time to close and go home
printf("Update parking info? Enter 0 to end");
scanf("%d",&updateVehicleParkingInfo);
/*
**** SENTINEL LOOP ****
Continue updating the parking info until the user wants to even for unlimited number of times.
Stop only when user enters a specific value i.e. 0.
*/
while(updateVehicleParkingInfo != 0){
printf("vehicle direction? 1 for entering, 0 for leaving:");
scanf("%d",&vehicleDirection);
if(vehicleDirection == VEHICLE_ENTERING){
do{
printf("Please enter parking Number:");
scanf("%d",&parkingIdx);
//*** CRASH ALERT!!! *** Following code can crash if parkingIdx is < 0, or >= MAX_PARKING_LOTS
//TODO: (1) Add sanity check for parkingIdx (2) Add corrective steps if sanity check fails
//if parking is not available, print an error message
if(vehicleParkingInfo[parkingIdx].parking.availability == PARKING_LOT_UNAVAILABLE){
//TODO: change the below messages to fine-tune fun, humor, teasing etc levels (remember humor setting of TARS from Interstellar?)
printf("There is some other vehicle parked in this parking lot, please enter another parking lot number\n");
printf("BTW, I know which lots are available, but I won't tell you ... hehehe >-) \n, keep trying ...hoo hoo hooo\n");
}
//check if the requested parking lot is available, if yes, then take further actions, else request a new parking lot number
}while(vehicleParkingInfo[parkingIdx].parking.availability == PARKING_LOT_UNAVAILABLE);
printf("Yipee, this parking lot is available\n");
//mark this parking lot number as being used so that another vehicle cannot come here.
vehicleParkingInfo[parkingIdx].parking.availability = PARKING_LOT_UNAVAILABLE;
//get vehicle type info and
// *** CRASH ALERT!!! *** The scanf below will crash if the user enters more 99+ characters (buffer overflow)
// Best is to use fgets or getline with the stdin as the stream.
// Ref /2723099/kak-mne-prochitat-stroku-vvedennuy-polzovatelem-v-c
// TODO: Replace below scanf() with a better/safer implmentation
printf("Enter Vehicle Type etc: suv,mpv and more:");
scanf("%s",vehicleParkingInfo[parkingIdx].vehicle.vecType);
//TODO: other steps.
}
if(vehicleDirection == VEHICLE_LEAVING){
do{
printf("Please enter parking Number:");
scanf("%d",&parkingIdx);
//*** CRASH ALERT!!! *** Following code can crash if parkingIdx is < 0, or >= MAX_PARKING_LOTS
//TODO: (1) Add sanity check for parkingIdx (2) Add corrective steps if sanity check fails
//if parking is available, print an error message
if(vehicleParkingInfo[parkingIdx].parking.availability == PARKING_LOT_AVAILABLE){
printf("It appears that the parking lot number is incorrect, please enter correct parking lot number\n");
}
//check if the requested parking lot is available, if yes, then request a new parking lot number, else proceed further
}while(vehicleParkingInfo[parkingIdx].parking.availability == PARKING_LOT_AVAILABLE);
printf("Bye bye, drive safely\n");
//mark this parking lot number as available for other incoming vehicles.
vehicleParkingInfo[parkingIdx].parking.availability = PARKING_LOT_AVAILABLE;
}
//get user's input if parking info needs to be updated or it is time to close and go home
printf("Update parking info? Enter 0 to end");
scanf("%d",&updateVehicleParkingInfo);
//TODO: remove the following line of code before running the program
YOU_ARE_TRAPPED_BY_THE_BIG_BAD_GREEN_SCARY_MONSTER;
//go back to while loop,
//check if the vehicle parking info needs to be updated,
//break if the user has entered 0
}//end of the Sentinel loop
//the above loop will run indefinitely. The user has quite a lot of ways to come out of the loop
//(1) Enter the sentinel value '0', (easiest path)
//(2) Somehow stop the program e.g. by banging his/her head really hard on the computer such that computer breaks .. etc
}//end of main()