2016-04-15 7 views
-1

私のコンピュータサイエンスクラスでの私の今後のプロジェクトでは、スターウォーズのクイズゲームを作る必要があります。ファイルからクラス型のベクトルに単語を入力する方法は?

ファイルstar_wars.txtには、キャラクターの名前と最初に登場したエピソードが含まれています(これはリリース日時に基づいています - 4,5,6,1,2,3) 。あなたは、star_wars.txtの内容でcastというベクトルを設定します。キャストベクトルの型はCharacterです。クラスCharacterは、star_wars.txtファイルと一致する属性(名、姓、エピソード)を持ちます。プログラムは、キャラクターが最初に登場したエピソードをユーザーに尋ねます。ユーザーに正しいかどうかを教えてください。どれだけ多くの人が正しいのかを把握し、スコアに基づいてランク付けします。 star_wars.txtの

例:私は最初と最後のベクトルと、ディスプレイには、このファイルを置くだろうか

アクバー提督6
ランド・カルリジアン5
等...

質問するときに名前?

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

class Character 
{ 
    private: 
    int score; 


    int episode; 
    int guess; 
    public: 
    void readIn(vector<Character>&cast); 
    void readOut(); 
    string first; 
    string last; 
}; 


int main() 
{ 
    Character ch; 
    vector<Character> cast; 
    cout<<"Welcome to the star wars quiz! I will tell you a character and you have to tell me what episode they first appeared in. Lets play!"<<endl; 
    ch.readIn(cast); 
    cout<<ch.first<<endl; 


    return 0; 
} 

void Character::readIn(vector<Character>&cast) 
{ 
    ifstream myFile("star_wars.txt"); 

    while (!myFile.eof()) 
    { 
    myFile>>first; 
    } 
} 

答えて

1

私は入力の中で読書の上に移動します。ここでは

は、私がこれまで持っているものです。表示は、あなた自身で把握するのに十分シンプルでなければなりません。

#include <istream> 
#include <string> 

class Character 
{ 
    private: 
    int score; 
    int guess; 

    public: 
    friend std::istream& operator>>(std::istream& is, Character& ch); 
    std::string first; 
    std::string last; 
    int episode; 
}; 

std::istream& operator>>(std::istream& is, Character& ch) 
{ 
    is >> ch.first >> ch.last >> ch.episode; 
    return is; 
} 

あなたがこれをしたら、あなたはこのように、文字を入力する>>を使用することができます:

int main() 
{ 
    Character ch; 
    cin >> ch; 
} 

あなたは何ができるか

は、あなたのCharacterクラスのoperator >>を作成することですepisodepublicセクションに移動しましたが、実際にはこれらのアイテムの公開にはgetsetの機能を公開する必要があります。 privateセクション。

また、クラス内にベクターを入れたくありません。あなたがしたいことは、クラスの外からベクターに項目を入力する方法があります。上記の例では、operator >>と出力のためのoperator <<両方の過負荷を示していること

#include <iterator> 
//... 
int main() 
{ 
    std::ifstream ifs("myinputfile.txt"); 
    std::istream_iterator<Character> fileStart(ifs), fileEnd; 
    std::vector<Character> vCh(FileStart, fileEnd); 
} 

Here is a live example

注:

int main() 
{ 
    std::ifstream ifs("myinputfile.txt"); 
    std::vector<Character> vCh; 
    while (ifs) 
    { 
     Character ch; 
     ifs >> ch; // read a line into ch 
     vCh.push_back(vCh); // add this to the vector 
    } 
} 

または洗練された方法:あなたはそれを長い道のりを行うことができます。私はそれが何であるかについては1行ごとには進みませんが、何が行われているかについてあなた自身の研究をすることができます。

関連する問題