2017-10-06 16 views
0

私はContestantInfo *contestantStructArray = new ContestantInfo [numberOfContestants];動的な構造体配列エラー

を作成しようとすると、エラー「不完全なタイプの割り当て」を取得していますHERESに私のコード:

#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もちろん、メインの前に構造体定義を置くだけでいいです。 – cnelmortimer

+0

愚かな単純な修正ありがとうございます。 –

0

ポインタを使用する理由はありますか?

新しい配列で動的配列を割り当てるのではなく、stdベクターを使用すると、より簡単になります。

構造体では、int型のベクトルとchar型のポインタの代わりに文字列のベクトルを持つことができます。

また、コンテスト情報のベクトルを表示することもできます。

これで、リソース管理を心配する必要がなくなり、標準テンプレートライブラリで処理できるようになります。

は、詳細はこちらをご覧ください:

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

+0

:この質問とその回答を参照してください。 –