C语言初学者求助:实现结构体读取月份数字转名称的函数
解决方案
直接给你修正后的可复用实现,核心是让月份转换函数能返回合法的字符串,方便在printf里直接调用:
#include <stdio.h> // 定义杂货店商品结构体 typedef struct { int month; // 存储1-12的月份数字 char item_name[50]; float price; } GroceryItem; // 月份转换函数:输入数字返回对应名称 const char* get_month_name(int month) { // 用静态数组存月份名称,比switch更简洁 static const char* months[] = { "无效月份", "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月" }; // 校验输入范围,防止越界 if (month < 1 || month > 12) { return months[0]; } return months[month]; } int main() { GroceryItem item; // 模拟用户输入流程 printf("输入商品月份(1-12):"); scanf("%d", &item.month); printf("输入商品名称:"); scanf("%s", item.item_name); printf("输入商品价格:"); scanf("%f", &item.price); // 直接在printf里调用转换函数 printf("\n商品信息:\n"); printf("月份:%s\n", get_month_name(item.month)); printf("名称:%s\n", item.item_name); printf("价格:%.2f\n", item.price); return 0; }
关键修正说明:
- 函数返回值设计:用
const char*作为返回类型,直接返回字符串字面量的地址,这样就能在printf的格式参数里直接调用,彻底解决复用问题。 - 避免野指针:用
static修饰月份数组,确保函数结束后数组不会被销毁,返回的地址始终有效。 - 鲁棒性提升:增加了月份范围校验,输入非法数字时会返回"无效月份"提示。
- 可维护性:用数组替代繁琐的switch分支,后续修改月份名称只需调整数组内容即可。
内容的提问来源于stack exchange,提问作者Koroza
相关产品推荐
相关产品推荐

