快速回忆C语言怎么写

示例代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 定义枚举类型
enum Grade {A, B, C, D, F};

// 定义结构体
struct Student {
    char name[50];
    int age;
    enum Grade grade;
};

// 函数声明
void inputStudent(struct Student *s);
void displayStudent(const struct Student *s);
void saveToFile(const struct Student *s, const char *filename);

int main() {
    struct Student students[100];
    int count = 0;
    char filename[] = "students.txt";
    
    // 输入学生信息
    for (int i = 0; i < 3; i++) { // 假设输入3个学生
        printf("Enter details for student %d:\n", i + 1);
        inputStudent(&students[count]);
        count++;
    }

    // 显示学生信息
    printf("\nStudent Details:\n");
    for (int i = 0; i < count; i++) {
        displayStudent(&students[i]);
    }

    // 保存到文件
    for (int i = 0; i < count; i++) {
        saveToFile(&students[i], filename);
    }

    printf("\nStudent details saved to %s\n", filename);
    return 0;
}

// 输入学生信息
void inputStudent(struct Student *s) {
    printf("Name: ");
    scanf("%s", s->name);
    printf("Age: ");
    scanf("%d", &s->age);
    printf("Grade (0=A, 1=B, 2=C, 3=D, 4=F): ");
    int grade;
    scanf("%d", &grade);
    s->grade = (enum Grade)grade;
}

// 显示学生信息
void displayStudent(const struct Student *s) {
    printf("Name: %s, Age: %d, Grade: %d\n", s->name, s->age, s->grade);
}

// 保存学生信息到文件
void saveToFile(const struct Student *s, const char *filename) {
    FILE *fp = fopen(filename, "a");
    if (fp == NULL) {
        perror("Error opening file");
        return;
    }
    fprintf(fp, "Name: %s, Age: %d, Grade: %d\n", s->name, s->age, s->grade);
    fclose(fp);
}

CheetSheet

C Cheat Sheet & Quick Reference

其它资源