设计一个酒店管理系统的C语言程序,要求输入的数据能输入到txt文档中保存和读取
时间: 2024-03-08 20:51:18 浏览: 23
好的,下面是一个简单的酒店管理系统的C语言程序,可以输入数据并将数据保存到txt文档中,也可以从txt文档中读取数据。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct hotel {
char name[20];
int room_num;
char address[50];
char phone[20];
};
int main() {
struct hotel h;
int choice, i, n;
FILE *fp;
fp = fopen("hotel.txt", "a+");
if (fp == NULL) {
printf("Error opening file!\n");
exit(1);
}
while (1) {
printf("\n1. Add hotel information\n");
printf("2. Display hotel information\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the number of hotels you want to add: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("\nEnter hotel name: ");
scanf("%s", h.name);
printf("Enter the number of rooms in the hotel: ");
scanf("%d", &h.room_num);
printf("Enter hotel address: ");
scanf("%s", h.address);
printf("Enter hotel phone number: ");
scanf("%s", h.phone);
fprintf(fp, "%s %d %s %s\n", h.name, h.room_num, h.address, h.phone);
}
printf("\nHotel information added successfully!\n");
break;
case 2:
rewind(fp);
printf("\nHotel information:\n\n");
while (fscanf(fp, "%s %d %s %s", h.name, &h.room_num, h.address, h.phone) != EOF) {
printf("Hotel Name: %s\n", h.name);
printf("Number of Rooms: %d\n", h.room_num);
printf("Address: %s\n", h.address);
printf("Phone Number: %s\n\n", h.phone);
}
break;
case 3:
fclose(fp);
exit(0);
default:
printf("\nInvalid choice!\n");
break;
}
}
return 0;
}
```
程序中使用了一个结构体`hotel`,包含了酒店的名称、房间数量、地址和电话号码。程序首先打开了一个名为`hotel.txt`的文本文件,如果文件不存在,则会提示错误并退出程序。接着,程序进入一个循环中,根据用户的选择执行不同的操作。如果用户选择添加酒店信息,则要求用户输入酒店的名称、房间数量、地址和电话号码,并将这些信息写入到文本文件中。如果用户选择查看酒店信息,则从文本文件中读取数据并输出到屏幕上。如果用户选择退出程序,则关闭文本文件并退出程序。
注意,程序中使用了`fopen`函数打开了一个文件,使用`fprintf`函数将数据写入文件中,使用`fscanf`函数从文件中读取数据,并使用`fclose`函数关闭文件。这些函数都是C语言标准库中的文件操作函数,可以实现将数据保存到文本文件中和从文本文件中读取数据的功能。