2016-04-15 134 views
-1

我試圖創建一個學生的結構,然後在那個結構裏面有一個基於用戶輸入的分數(或標記)如何標記。創建結構元素的動態數組,然後創建結構的動態數組。 C++

然後我試圖創建一個Student結構的動態數組。

我想與這些指針進行交互,即輸入學生信息和成績然後cout他們但是我不認爲我正在做這個。這是我的代碼的一部分開始。我的主要問題是創建一系列標記,我無法在我的教科書中找到如何聲明它。

#include <string.h> 
#include <iostream> 
#include <sstream> 
using namespace std; 


struct Student 
{ 
    string name; 
    int id; 
    int* mark; 
    ~Student() 
{ 
    delete [] mark; 
    mark = NULL; 
}; 
}; 

void initStudent(Student* ptr, int markNum, int studentNum); // function prototype for initialization 
void sayStudent(Student* ptr, int markNum, int studentNum);  // function prototype for printing 

//*********************** Main Function ************************// 
int main() 
{ 
    int marks, studentNum; 
    Student stu;   // instantiating an STUDENT object 
    Student* stuPtr = &stu; // defining a pointer for the object 
    cout << "How many marks are there? "; 
    cin >> marks; 
    cout << "How many students are there?"; 
    cin >> studentNum; 
    Student* mark = new int[marks]; 
    Student* students = new Student[studentNum]; 

    initStudent(students,marks,studentNum);  // initializing the object 
    sayStudent(students,marks,studentNum);  // printing the object 
    delete [] students; 

return 0; 

} // end main 

//-----------------Start of functions----------------------------// 

void initStudent(Student* ptr, int markNum, int studentNum) 
{ 
    for (int i = 0; i < studentNum; i++) 
    { 

     cout << "Enter Student " << i+1 << " Name :"; 
     cin >> ptr[i].name; 
     cout << "Enter Student ID Number :"; 
     cin >> ptr[i].id; 
     for (int j = 0; j < markNum; j++) 
     { 
     cout << "Please enter a mark :"; 
     cin >> ptr[i].mark[j]; 
     } 
    } 
    } 
+1

*我找不到我的教科書如何聲明它。* - '的std ::矢量''的std ::向量' - 獲取另一課本。 – PaulMcKenzie

+0

@PaulMcKenzie我需要動態分配內存。不只是創建一個矢量。 –

+1

@RoyGunderson _「我需要動態分配內存。」_你認爲'std :: vector'實際上有什麼作用? –

回答

0

您需要在每個Student元件分配marks陣列。

Student* students = new Student[studentNum]; 
for (int i = 0; i < studentNum; i++) { 
    students[i].mark = new int[marks]; 
} 

你也可以在initStudent

void initStudent(Student* ptr, int markNum, int studentNum) 
{ 
    for (int i = 0; i < studentNum; i++) 
    { 

     cout << "Enter Student " << i+1 << " Name :"; 
     cin >> ptr[i].name; 
     cout << "Enter Student ID Number :"; 
     cin >> ptr[i].id; 
     ptr[i].mark = new int[markNum] 
     for (int j = 0; j < markNum; j++) 
     { 
      cout << "Please enter a mark :"; 
      cin >> ptr[i].mark[j]; 
     } 
    } 
    } 
+0

謝謝你這麼多。她的作品完美無瑕。 –