2017-10-17 80 views
-8

我是编程新手,数组很弱。这里是编码和问题,请告诉我,如果我做了任何错误,我卡在阵列部分。C++数组 - 创建一个结构员工和显示的动态数组

Question

#include<iostream> 
#include<string> 
using namespace std; 

struct Library 
{ 
    string Name[10]; 
    int ID[10],Unit[10]; 
    double Price[10]; 
}; 

struct Library L; 
int main() 
{ 
    int book; 
    cout<<"Enter the number of book : "; 
    cin>>book; 
    for(int i=0; i<book; i++) 
    { 
    cout<<"\nBook Name : "; 
    cin>>L.Name[i]; 
    cout<<"Book ID : "; 
    cin>>L.ID[i]; 
    cout<<"Unit : "; 
    cin>>L.Unit[i]; 
    cout<<"Price : "; 
    cin>>L.Price[i];  
    } 
    cout<<"You have entered these info : "; 
    cout<<"\nName \t ID \t Unit Price"; 
    for(int i=0; i<book; i++) 
    { 
    cout<<"\n"<<L.Name[i]<<endl; cout<<"\t"<<L.ID<<"\t"<<L.Unit<<"\t"<<L.Price<<endl; 
    } 

} 
+2

你有没有试过** **呢?它有用吗? – Steve

+0

除了名称全部显示错误代码(0x4a7090) – Zeshon

+0

@Zeshon我认为它是动态分配的数组(不分配)结构类型的对象应该命名为Library,并且结构本身应该命名为Book。 –

回答

0

修复了你的小错误。动态地为内存结构数组动态分配内存,只需1行。

试一下:https://ideone.com/5KUKkV

你把输入的书籍号码后,您必须这样做:

struct Library *L = new Library[book]; 

你在你的结构访问每个成员的方式是L[i].ID, L[i].Name等。 。

此外,您的结构成员无效。请参阅代码的正确性。

完整代码:

struct Library 
{ 
    string Name; 
    int ID, Unit; 
    double Price; 
}; 


int main() 
{ 

    int book; 
    cout << "Enter the number of book : "; 
    cin >> book; 

    struct Library *L = new Library[book]; 

    for (int i = 0; i<book; i++) 
    { 
     cout << "\nBook Name : "; 
     cin>>L[i].Name; 
     cout << "Book ID : "; 
     cin >> L[i].ID; 
     cout << "Unit : "; 
     cin >> L[i].Unit; 
     cout << "Price : "; 
     cin >> L[i].Price; 
    } 
    cout << "You have entered these info : "; 
    cout << "\nName \t ID \t Unit Price"; 
    for (int i = 0; i<book; i++) 
    { 
     cout << "\n" << L[i].Name << endl; cout << "\t" << L[i].ID << "\t" << L[i].Unit << "\t" << L[i].Price << endl; 
    } 

} 
0

而不是在struct,我建议该结构的阵列(如你的问题的标题和分配)阵列:

struct Library 
{ 
    string Name; 
    int ID; 
    int Unit; 
    double Price; 
}; 

如果你必须使用动态内存分配,你可以创建你的收藏为:

Book * Collection = new Library[10]; 
0

使用结构的向量:

#include<iostream> 
#include<string> 
using namespace std; 

struct Library 
{ 
    string Name; 
    int ID,Unit; 
    double Price; 
}; 

int main() 
{ 
    vector<Library> L; 
    Library tempL; 
    int book; 
    cout<<"Enter the number of book : "; 
    cin>>book; 

    for(int i=0; i<book; i++) 
    { 
    cout<<"\nBook Name : "; 
    cin>>tempL.Name; 
    cout<<"Book ID : "; 
    cin>>tempL.ID; 
    cout<<"Unit : "; 
    cin>>tempL.Unit; 
    cout<<"Price : "; 
    cin>>tempL.Price;  
    l.push_back(tempL); 
    } 
    cout<<"You have entered these info : "; 
    cout<<"\nName \t ID \t Unit Price"; 
    for(int i=0; i<L.size(); i++) 
    { 
    cout<<"\n"<<L[i].Name<<endl; 
    cout<<"\t"<<L[i].ID<<"\t"<<L.Unit<<"\t"<<L[i].Price<<endl; 
    } 
} 
+0

太糟糕了,您的更改不符合作业的*“动态数组”*部分。这可能是关于动态内存分配的一个教训,使用'new'和数组。 –

+0

另外,不喜欢做人的功课。相反给他们提示或引导他们。如果你做功课,他们不会学习。 –