2017-10-06 87 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

是分配限制我们只有我们动态数组。 –