易百教程

结构体数组

请阅读以下代码,以了解在C语言中如何使用结构数组。

示例代码

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <ctype.h>

typedef struct Dog Dog;  // 定义 Dog 作为一个类型名称

struct Dog  // 结构体类型定义
{
    int age;
    int height;
    char name[20];
    char father[20];
    char mother[20];
};

int main(void)
{
    Dog my_dogs[50];                 // Dog数组的元素数量
    int dog_Count = 0;               //计算Dog的数量
    char test = '\0';                // 测试值的结尾

    for (dog_Count = 0; dog_Count < sizeof(my_dogs) / sizeof(Dog); ++dog_Count)
    {
        printf_s("Do you want to enter details of a%s dog (Y or N)? ",
            dog_Count ? "nother" : "");
        scanf_s(" %c", &test, sizeof(test));
        if (tolower(test) == 'n')
            break;

        printf_s("Enter the name of the dog: ");
        scanf_s("%s", my_dogs[dog_Count].name, sizeof(my_dogs[dog_Count].name));

        printf_s("How old is %s? ", my_dogs[dog_Count].name);
        scanf_s("%d", &my_dogs[dog_Count].age);

        printf_s("How high is %s ( in hands )? ", my_dogs[dog_Count].name);
        scanf_s("%d", &my_dogs[dog_Count].height);

        printf_s("Who is %s's father? ", my_dogs[dog_Count].name);
        scanf_s("%s", my_dogs[dog_Count].father, sizeof(my_dogs[dog_Count].father));

        printf_s("Who is %s's mother? ", my_dogs[dog_Count].name);
        scanf_s("%s", my_dogs[dog_Count].mother, sizeof(my_dogs[dog_Count].mother));
    }
    // 打印结果值
    printf_s("\n");
    for (int i = 0; i < dog_Count; ++i)
    {
        printf_s("%s is %d years old, %d hands high,",
            my_dogs[i].name, my_dogs[i].age, my_dogs[i].height);
        printf_s(" and has %s and %s as parents.\n", my_dogs[i].father,
            my_dogs[i].mother);
    }
    system("pause");
    return 0;
}

执行上面示例代码,得到以下结果:

Do you want to enter details of a dog (Y or N)? Y
Enter the name of the dog: HeiPi
How old is HeiPi? 2
How high is HeiPi ( in hands )? 2
Who is HeiPi's father? HeiPi他爸
Who is HeiPi's mother? HeiPi他妈
Do you want to enter details of another dog (Y or N)? n

HeiPi is 2 years old, 2 hands high, and has HeiPi他爸 and HeiPi他妈 as parents.