我开始开发一个将使用结构体数组的程序,但是我的程序在仅循环一次通过数组的输入后立即结束。该代码可用于单个维度数组,但是当我合并另一个维度时会失败。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Define a structure to hold the items
typedef struct {
char name[20];
int quantity;
} item;
// Declare an array of structures
//struct item shelves[2];
item shelves[2][2];
int main(void) {
// Loop to input 4 items
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("\nEnter the item name: ");
scanf("%s", shelves[i][j].name);
printf("\nEnter the item quanity: ");
scanf("%d", shelves[i][j].quantity);
}
}
// Print two blank lines
printf("\n\n");
// Loop to display the data
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("Name: %s", shelves[i][j].name);
printf("\nQuantity: %d", shelves[i][j].quantity);
}
}
return 0;
}
这是我运行此代码时的样子: Terminal Window