在C++中访问结构的变量?

Accessing structure's variable in C++?

本文关键字:变量 结构 访问 C++      更新时间:2023-10-16
struct app
{   int id;
    char name[20];
    char developer[20];
    char type[20];
    int date_uploaded [3];
};
.
.
.
void search(app a[2])
{
    int choice;
    char t_check[20];
    Dhome();
    cout<<"nnSelect the way you want to search for an app"
        <<"n(1) To search by app name"
        <<"n(2) To search by developer name"
        <<"n(3) To search by type"
        <<"n(4) To return to previous menun";
    cin>>choice;
    cin.ignore();
    switch(choice)
    {
        case 1:
            Dhome();
            cout<<"nnEnter the app's name: ";
            search_specific(a,"name");
            //Similar cases for passing developer and type
    }
}
void search_specific(app a[2], char choice[10])
    {   int i, flag=0;
        char t_check[20], s_type[5];
        gets(t_check);
        for(i=0; i<2; i++)
        {
        if(strcmp(t_check, a[i].choice)==0)
            {
                flag=1;
                break;
            }
        }
        if(flag==1)
        {
            cout<<"nThe app was found and its details are as below"
                <<"nApp ID: "<<a[i].id
                <<"nApp Name: "<<a[i].name
                <<"nDeveloper Name: "<<a[i].developer
                <<"nType: "<<a[i].type
                <<"nDate Uploaded: "<<a[i].date_uploaded[0]<<"/"<<a[i].date_uploaded[1]<<"/<<a[i].date_uploaded[2];
            cout<<"nnPress enter to return to the previous menu";
            getch();
            return;
        }
        if(flag==0)
        {
            cout<<"nThe app was not found";
            cout<<"nnPress enter to return to the previous menu";
            getch();
            return;
        }
    }

现在的问题是我不能使用 a[i].choice,因为编译器试图在结构应用程序中找到"选择"。我希望它引用其值,即名称、开发人员或类型。我怎样才能做到这一点?

您必须制定一个 switch 语句,读取类型为 app 的值的所需成员,如下所示。

int choice;
// read choice from somewhere
switch(choice)
{
    case 0:
        // do something with a[i].id
        break;
    case 1:
        // do something with a[i].name
        break;
    default;
        break;
}

无法按索引访问结构的成员。

C++ 语言不提供可以在运行时反映的一流属性,就像 JavaScript 那样。所以你的问题没有一行的答案。也许最接近您要找的东西的是 std::map .但是,如果您使用的是像 app 这样的结构,则必须编写自己的代码来从对象中获取每个字段,如 Codor 的示例所示。