You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言如何不用编写365次就能在struct中创建多个可区分成员存储日记

解决方案

1. 实现思路

你不需要手动定义365个结构体变量,只需要先把结构体定义为单天日记的存储单元,再声明该类型的数组即可,数组长度直接设为365就能存满一整年的日记,通过数组下标就可以循环操作每一天的记录。

2. 修正后的完整代码

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

// 结构体定义:存储单天的日记内容
struct Diary {
    char day[20];    // 存储星期几,比如"周一",长度按需调整即可
    char date[30];   // 存储日期,比如"2024-05-20"
    char time[20];   // 存储记录时间
    char place[50];  // 存储地点
    char content[500]; // 存储日记内容,长度可按需调整
};

int main() {
    // 声明结构体数组,最多存365天的日记,通过下标即可访问任意一天的记录
    struct Diary year_diary[365];
    int count = 0; // 记录当前已录入的日记条数
    int exit_flag = 1;

    while(exit_flag != 0 && count < 365) {
        printf("===== 第%d天日记录入 =====\n", count+1);
        printf("Enter Day:");
        // 替换不安全的gets函数,用fgets避免缓冲区溢出
        fgets(year_diary[count].day, sizeof(year_diary[count].day), stdin);
        // 去掉fgets读取到的末尾换行符
        year_diary[count].day[strcspn(year_diary[count].day, "\n")] = '\0';

        printf("Enter Date:");
        fgets(year_diary[count].date, sizeof(year_diary[count].date), stdin);
        year_diary[count].date[strcspn(year_diary[count].date, "\n")] = '\0';

        printf("Enter Time:");
        fgets(year_diary[count].time, sizeof(year_diary[count].time), stdin);
        year_diary[count].time[strcspn(year_diary[count].time, "\n")] = '\0';

        printf("Enter Place:");
        fgets(year_diary[count].place, sizeof(year_diary[count].place), stdin);
        year_diary[count].place[strcspn(year_diary[count].place, "\n")] = '\0';

        printf("Tell me about your day:");
        fgets(year_diary[count].content, sizeof(year_diary[count].content), stdin);
        year_diary[count].content[strcspn(year_diary[count].content, "\n")] = '\0';

        // 打印当前录入的内容
        printf("\n\n===== 已录入的第%d天日记 =====\n", count+1);
        printf("Day: %s\n", year_diary[count].day);
        printf("Date: %s\n", year_diary[count].date);
        printf("Time: %s\n", year_diary[count].time);
        printf("Place: %s\n", year_diary[count].place);
        printf("Content: %s\n\n\n", year_diary[count].content);

        count++;
        printf("输入0结束录入,输入其他数字继续录入下一天:");
        scanf("%d", &exit_flag);
        getchar(); // 吃掉scanf留下的换行符,避免后续fgets读空
    }

    // 可直接循环遍历所有已录入的日记,示例如下
    printf("===== 所有已录入的日记 =====\n");
    for(int i=0; i<count; i++) {
        printf("第%d天:\n日期:%s,内容概要:%.20s...\n", i+1, year_diary[i].date, year_diary[i].content);
    }

    return 0;
}

核心改动说明

  • 结构体Diary现在对应单天的所有日记字段,不再把字段长度设为365,而是按实际存储的内容长度设置即可,避免空间浪费
  • 直接声明struct Diary year_diary[365]结构体数组,相当于一次性创建了365个独立的结构体实例,每个实例对应一天的日记,用year_diary[下标]就可以访问任意一天的记录,完全不需要手动定义365个变量
  • 替换了原代码中不安全的gets()函数,改用fgets()避免缓冲区溢出问题,同时处理了换行符残留的问题
  • 增加了录入计数控制,最多录入365天,也支持手动提前结束录入

内容的提问来源于stack exchange,提问作者RustyGAWWD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 14:45:00