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

时间:2014-12-16 07:31:35

标签: c++

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<<"\n\nSelect 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 menu\n";
    cin>>choice;
    cin.ignore();
    switch(choice)
    {
        case 1:
            Dhome();
            cout<<"\n\nEnter 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<<"\n\nPress enter to return to the previous menu";
            getch();
            return;
        }
        if(flag==0)
        {
            cout<<"\nThe app was not found";
            cout<<"\n\nPress enter to return to the previous menu";
            getch();
            return;
        }

    }

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

2 个答案:

答案 0 :(得分:1)

您必须制定一个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;
}

无法以索引方式访问结构的成员。

答案 1 :(得分:0)

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