实验题目:模拟饭卡充值一、实验内容1.录入几位学生信息(姓名,学号,饭卡余额),并保存到student.txt文件中;2.能够依据学号对饭卡充值,每次充值的金额为10的倍数;3.能够按照学号查询饭卡余额,如果谁的余额少于10元,就给出充值提示。要求:软件至少应具有“输入初始数据”、“饭卡充值”、“查询余额”、“退出”4项菜单。要求使用c语言编写,程序尽可能简单,并在每一步程序后面注释其作用
时间: 2023-12-26 13:03:46 浏览: 160
很抱歉,我并不是一个可以运行代码的程序,但我可以为您提供思路和解释。
首先,我们需要定义一个结构体来存储学生信息,包括姓名、学号和饭卡余额:
```c
struct Student {
char name[20];
int id;
int balance;
};
```
然后,我们需要实现以下功能:
1. 输入初始数据并保存到文件中
```c
void input_students() {
FILE *fp;
struct Student student;
fp = fopen("student.txt", "w");
if (fp == NULL) {
printf("Error: Cannot open file!\n");
return;
}
printf("Enter student information:\n");
printf("Name: ");
scanf("%s", student.name);
printf("ID: ");
scanf("%d", &student.id);
printf("Balance: ");
scanf("%d", &student.balance);
fprintf(fp, "%s %d %d\n", student.name, student.id, student.balance);
fclose(fp);
printf("Saved to file successfully!\n");
}
```
2. 饭卡充值
```c
void recharge() {
FILE *fp;
struct Student student;
int id, amount;
printf("Enter student ID: ");
scanf("%d", &id);
printf("Enter recharge amount (must be multiple of 10): ");
scanf("%d", &amount);
if (amount % 10 != 0) {
printf("Error: Recharge amount must be multiple of 10!\n");
return;
}
fp = fopen("student.txt", "r+");
if (fp == NULL) {
printf("Error: Cannot open file!\n");
return;
}
while (fscanf(fp, "%s %d %d", student.name, &student.id, &student.balance) != EOF) {
if (student.id == id) {
student.balance += amount;
fseek(fp, -sizeof(student), SEEK_CUR);
fprintf(fp, "%s %d %d", student.name, student.id, student.balance);
printf("Recharge successfully!\n");
break;
}
}
fclose(fp);
if (feof(fp)) {
printf("Error: Student not found!\n");
}
}
```
3. 查询余额
```c
void check_balance() {
FILE *fp;
struct Student student;
int id;
printf("Enter student ID: ");
scanf("%d", &id);
fp = fopen("student.txt", "r");
if (fp == NULL) {
printf("Error: Cannot open file!\n");
return;
}
while (fscanf(fp, "%s %d %d", student.name, &student.id, &student.balance) != EOF) {
if (student.id == id) {
printf("Balance: %d\n", student.balance);
if (student.balance < 10) {
printf("Warning: Balance is less than 10, please recharge!\n");
}
break;
}
}
fclose(fp);
if (feof(fp)) {
printf("Error: Student not found!\n");
}
}
```
4. 退出
```c
void exit_program() {
printf("Goodbye!\n");
exit(0);
}
```
最后,我们需要实现一个菜单来调用这些功能:
```c
int main() {
int choice;
while (1) {
printf("Menu:\n");
printf("1. Input initial data\n");
printf("2. Recharge\n");
printf("3. Check balance\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
input_students();
break;
case 2:
recharge();
break;
case 3:
check_balance();
break;
case 4:
exit_program();
break;
default:
printf("Error: Invalid choice!\n");
}
}
return 0;
}
```
以上就是一个简单的模拟饭卡充值的程序,希望能帮助到您!
阅读全文