2017-10-06 84 views
0

我得到的錯誤,當我嘗試創建ContestantInfo *contestantStructArray = new ContestantInfo [numberOfContestants];動態結構陣列錯誤

繼承人我的代碼「不完全類型的分配」:

#include <fstream> 
#include <iostream> 

using namespace std; 

struct ContestantInfo; 

int main() 
{ 
    //opens all the files for input and output 
    fstream contestantsFile("contestants.txt", ios::in); 
    fstream answerKeyFile("answers.txt", ios::in); 
    fstream reportFile("report.txt", ios::out); 

    //used to determine how many contestants are in the file 
    int numberOfContestants = 0; 
    string temp; 

    //checks to see if the files opened correctly 
    if(contestantsFile.is_open() && answerKeyFile.is_open() && reportFile.is_open()){ 

     //counts the number of lines in contestants.txt 
     while(getline(contestantsFile, temp, '\n')){ 

      numberOfContestants++; 

     } 

     //Puts the read point of the file back at the beginning 
     contestantsFile.clear(); 
     contestantsFile.seekg(0, contestantsFile.beg); 

     //dynamic array that holds all the contestants ids 
     string *contestantIDNumbers = new string [numberOfContestants]; 

     //Reads from the contestants file and initilise the array 
     for(int i = 0; i < numberOfContestants; i++){ 

      getline(contestantsFile, temp, ' '); 

      *(contestantIDNumbers + i) = temp; 

      //skips the read point to the next id 
      contestantsFile.ignore(256, '\n'); 

     } 

     ContestantInfo *contestantStructArray = new ContestantInfo [numberOfContestants]; 

    } 
    else 
    { 
     cout << "ERROR could not open file!" << endl; 
     return 0; 
    } 

} 

struct ContestantInfo{ 

    string ID; 
    float score; 
    char *contestantAnswers; 
    int *questionsMissed; 

}; 

Struct ContestantInfo的指針最終應該指向動態數組以及如果改變任何東西。我是一名學生,所以如果我正在做一些愚蠢的事情,請不要猶豫。

回答

1

根據編譯器,你的問題是結構的向前聲明(當你試圖創建它們的數組)。看到這個問題,它的答案是:Forward declaration of struct

問候

+0

好吧我粗略瞭解那篇文章。你能提出一個包含可以解決這個問題的代碼,或者創建一個像這樣的動態結構數組只是不起作用嗎? –

+0

@FinnWilliams當然,你只需要把結構定義放在main之前。 – cnelmortimer

+0

愚蠢簡單的修復謝謝你。 –

0

是否有任何理由需要使用指針?

如果你使用std向量而不是新的動態數組分配,它會讓事情變得更直接。

在你的結構中,你可以有一個向量,如果整數和一個字符串向量,而不是指向char的向量。

你也可以有一個矢量的參賽資訊。

然後您不需要擔心資源管理,並且可以讓標準模板庫處理它。

這裏看到更多的信息:

http://www.cplusplus.com/reference/vector/vector/

+0

是分配限制我們只有我們動態數組。 –