为什么类型结构的数组不能正常工作?

时间:2015-05-28 02:08:20

标签: c++ arrays struct operators

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{   
    struct data
    {
        string country;
        string fathername;
        int   age;
    };
        data NAME;

    data name[5]={"Ali", "Usman", "Sarmad", "Awais", "Junaid"};
    name[0]=(struct data){"Saudi Arabia","Tahir Awan",24};
    name[1]=(struct data){"England","Akram Khan",20};
    name[2]=(struct data){"China","Amjad Ali",20};
    name[3]=(struct data){"Syria","Ahmad Ali",19};
    name[4]=(struct data){"Oman","Zohaib Sultan",24};

            cout << "Enter Name of student/n";
            cin >>  NAME;

    int j;
    for(int i=0; i<6; i++)
    {
        if(NAME==name[i])
        j=i;
    }
    cout << "We have following data for   " << name[j]<< endl;
    cout << "Country:  " << name[j].country << endl << "Father name:  " << name[j].fathername << endl << "Age:  " << name[j].age << endl;

    return 0;

}

它给我带来了错误的数组初始化以及更多的错误。我尝试了很多找到错误的原因但不能。请在编译器中编译它并告诉我如何删除错误。还请告诉我错误的原因。

1 个答案:

答案 0 :(得分:2)

您不能通过传递字符串来初始化data类型的元素,因为它还需要另一个字符串和一个整数。您可以改用以下内容:

data name[5] = {
    {"Saudi Arabia","Tahir Awan",24},
    {"England","Akram Khan",20},
    {"China","Amjad Ali",20},
    {"Syria","Ahmad Ali",19},
    {"Oman","Zohaib Sultan",24}
};

Live demo