C语言关于定义结构体

从键盘输入3个人的姓名和电话号码,编程实现根据姓名或电话号码进行查询的功能。 【提示】定义结构体 per,包含成员:name[20]表示姓名,phone[20]表示电话码。姓 名和电话号码的比较可使用字符串库函 数 strcmp()实现,增加头文件#include 输入2表示根据电话号码进行查询,输入0表示 另外要求输入1表示根据姓名进行查询,结束。


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

#define N 3 

typedef struct person
{
    char name[20];
    char phone[20];
} person;

int main()
{
    person contacts[N];
    int i, choice;
    char query[20];
    
    for (i = 0; i < N; ++i)
    {
        printf("Please enter the name and phone of person %d (no space in person's name): ", i + 1);
        scanf("%s%s", contacts[i].name, contacts[i].phone);
    }
    
    while (1)
    {
        printf("Please enter 1 and name to query, or 2 phone to query, or 0 to exit: ");
        scanf("%d", &choice);
        if (choice == 0)
            break;
        else if (choice == 1)
        {
            scanf("%s", query);
            for (i = 0; i < N; ++i)
            {
                if (strcmp(contacts[i].name, query) == 0)
                {
                    printf("Found name [%s} and its phone is [%s].\n", query, contacts[i].phone);
                    break;
                }
            }
                
            if (i == N)
            {
                printf("Not found.\n");
            }
        }
        else if (choice == 2)
        {
            scanf("%s", query);
            for (i = 0; i < N; ++i)
            {
                if (strcmp(contacts[i].phone, query) == 0)
                {
                    printf("Found phone [%s} and its name is [%s].\n", query, contacts[i].name);
                    break;
                }
            }
            
            if (i == N)
            {
                printf("Not found.\n");
            }
        }
        else
        {
            printf("Invalid choice [%d].\n", choice);
        }
        fflush(stdin); // clear inout buffer in case there are extra cahracters in the previous input
    }
    
    return 0;
}

// Output:
Please enter the name and phone of person 1 (no space in person's name): ZhangSan 01065879876
Please enter the name and phone of person 2 (no space in person's name): LiSi 13888789900
Please enter the name and phone of person 3 (no space in person's name): WangWu 02123459876
Please enter 1 and name to query, or 2 phone to query, or 0 to exit: 1 ZhangSan
Found name [ZhangSan} and its phone is [01065879876].
Please enter 1 and name to query, or 2 phone to query, or 0 to exit: 1 ZhaoLiu
Not found.
Please enter 1 and name to query, or 2 phone to query, or 0 to exit: 2 02123459876
Found phone [02123459876} and its name is [WangWu].
Please enter 1 and name to query, or 2 phone to query, or 0 to exit: 2 13899990000
Not found.
Please enter 1 and name to query, or 2 phone to query, or 0 to exit: 3
Invalid choice [3].
Please enter 1 and name to query, or 2 phone to query, or 0 to exit: 0