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

C语言:填充食品杂货结构体数组失败,仅首个元素生效

问题分析:ShoppingList数组填充失败的原因及解决办法

结构体定义

#define MAX 256 // 假设MAX是你已定义的常量

struct GroceryItem {
   char productName[MAX];
   float amount;
   char unit[MAX];
};

struct ShoppingList {
   struct GroceryItem itemList[5];
   int length;
};

存在问题的填充函数

void addItem(struct ShoppingList *list)
{
int i = 0;
struct ShoppingList temp;

for (i = 0; i <=4; i++)
{  
    printf("Add an item: \n");
    while (getchar() != '\n');
    fgets(list->itemList[i].productName, MAX, stdin);
}
}

问题出在哪

  1. 循环里的getchar()清空逻辑顺序错误:第一次执行时,printf提示后你输入商品名按回车,fgets会读取包括回车的内容。但到第二次循环,while (getchar() != '\n')会卡住等待你输入回车——此时输入缓冲区是空的,这个循环会强制你多敲一次回车,而后面的fgets会把这个回车读成空字符串,导致后续的productName全是空的,看起来就像没填充成功。
  2. 函数里的struct ShoppingList temp;完全没用,属于冗余代码,删掉即可。

修复后的代码

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

#define MAX 256

void addItem(struct ShoppingList *list)
{
    int i = 0;
    list->length = 0; // 初始化已添加元素数量

    // 先清空之前可能残留的输入缓冲区内容
    int c;
    while ((c = getchar()) != '\n' && c != EOF);

    for (i = 0; i < 5; i++)
    {  
        printf("输入第%d个商品名称: ", i+1);
        if (fgets(list->itemList[i].productName, MAX, stdin) != NULL)
        {
            // 去掉fgets自带的换行符,避免字符串末尾带回车
            list->itemList[i].productName[strcspn(list->itemList[i].productName, "\n")] = '\0';
            list->length++;
        }
    }
}

额外提示

  • strcspn函数用来找到字符串中第一个换行符的位置,直接替换成结束符'\0',能让存储的商品名更干净。
  • 初始化list->length可以方便后续遍历已添加的商品,不用每次都遍历整个数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:55:25