0

最初は空で、withing、string、2 int、1floatの4つのデータ型を持つ構造化配列があります。DVDタイトルとその他の属性のリスト(他の3つ、最後の1つはfloatです)がテキストファイルに保存されており、テキストファイルから構造にデータを入力する必要があります。これは私のコードですが、機能していないようですか?

        do
        {
           for(int i=0;i<MAX_BOOKS;i++)
           {

                tempTitle= getline(myfile,line);
                temChapters = getline(myfile,line);
                tempReview = getline(myfile,line);
                tempPrice = getline(myfile,line);
           }
        }while(!myfile.eof());
4

2 に答える 2

5

戻り値getlineは、データを読み取った文字列ではなく、読み取ったストリームです。

lineまた、データをどこにも保存せずに、同じ場所 ( ) にデータを繰り返し読み取っています。

ループに欠陥while (!somefile.eof())があります (基本的に常に壊れています)。

通常必要なのは、オーバーロードoperator>>してストリームから単一の論理アイテムを読み取り、それを使用してそれらのアイテムのベクトルを埋めることです。

// The structure of a single item:
struct item { 
    std::string title;
    int chapters;
    int review;
    int price;    
};

// read one item from a stream:
std::istream &operator>>(std::istream &is, item &i) { 
    std::getline(is, i.title);
    is >> i.chapters >> i.review >> i.price;
    is.ignore(4096, '\n'); // ignore through end of line.
    return is;
}

// create a vector of items from a stream of items:
std::vector<item> items((std::istream_iterator<item>(myfile)), 
                         std::istream_iterator<item>());
于 2013-02-13T00:38:06.627 に答える