图书馆占座系统c语言程序
时间: 2023-10-01 10:04:33 浏览: 46
以下是一个简单的图书馆占座系统的C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 20
#define NUM_SEATS 10
typedef struct {
int id;
char name[MAX_NAME_LEN];
int reserved;
} Seat;
void print_seats(Seat seats[]) {
printf("Current seat reservations:\n");
for (int i = 0; i < NUM_SEATS; i++) {
if (seats[i].reserved == 0) {
printf("Seat %d: vacant\n", seats[i].id);
} else {
printf("Seat %d: reserved by %s\n", seats[i].id, seats[i].name);
}
}
}
int main() {
Seat seats[NUM_SEATS];
char input[MAX_NAME_LEN];
int seat_num;
int num_reserved = 0;
// initialize seats
for (int i = 0; i < NUM_SEATS; i++) {
seats[i].id = i+1;
seats[i].reserved = 0;
}
// main loop
while (1) {
print_seats(seats);
printf("Enter your name to reserve a seat (or 'quit' to exit): ");
fgets(input, MAX_NAME_LEN, stdin);
if (strcmp(input, "quit\n") == 0) {
break;
}
input[strlen(input)-1] = '\0'; // remove newline character
printf("Enter seat number to reserve (1-%d): ", NUM_SEATS);
scanf("%d", &seat_num);
getchar(); // consume newline character
// check if seat is already reserved
if (seats[seat_num-1].reserved == 1) {
printf("Sorry, seat %d is already reserved.\n", seat_num);
continue;
}
// reserve the seat
seats[seat_num-1].reserved = 1;
strcpy(seats[seat_num-1].name, input);
num_reserved++;
printf("Seat %d reserved by %s.\n", seat_num, input);
}
printf("Goodbye! %d seats reserved.\n", num_reserved);
return 0;
}
```
该程序使用了一个简单的结构体来表示座位,其中包含了座位编号、座位预约者的姓名和是否已经被预约。程序提供了一个 `print_seats()` 函数来打印当前的座位预约情况。在主循环中,程序会要求用户输入姓名和座位号来进行预约。程序会检查该座位是否已经被预约,如果是,则提示用户重新选择。如果该座位尚未被预约,则程序会将该座位的预约状态设置为已预约,并将预约者的姓名保存在座位数据结构中。程序会一直循环直到用户输入 `quit` 为止。最后程序会输出预约座位的数量,并退出程序。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)