C ++ I / O流文本文件到数组问题

时间:2011-11-23 11:24:14

标签: c++ file-io iostream

我的代码应该从文本文件读取16行,并将它们传递给4个对象的数组,每个对象有4个属性。我遇到的问题是,虽然在将文本细节传递给数组时一切似乎都能正常工作,但数组中最后一个对象的第一个数组元素不应该是那个!我真的被卡住了!

我的代码是:

#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

int CDsize;

class CD {
public:
    // constructors
    CD();
    CD(string arist, string title, int year, double price);

    // getter methods
    string getArtist() const { return this->artist; }
    string getTitle() const { return this->title; }
    int getYear() const { return this->year; }
    double getPrice() const { return this->price; }

    // setter methods - inline functions
    void setArtist(const string artist) { this->artist = artist; }
    void setTitle(const string title) { this->title = title; }
    void setYear(const int year) { this->year = year; }
    void setPrice(const double price) { this->price = price; }

    // option methods
private:
    string artist;
    string title;
    int year;
    double price;
};

/*Text menu option 1/*
void printallcds(CD MAX_CDS[])
{
     int d;
  for (d=0; d<=CDsize; d++)

  {
    cout << "CD Number : " << d << "/ Artist : " << MAX_CDS[d].getArtist() << "/
Title : " << cout << MAX_CDS[d].getTitle() << "/ Year of Release : " <<
MAX_CDS[d].getYear() << "/ Price : " <<
  cout << MAX_CDS[d].getPrice() << endl;
  }
}*/

int main() {
    CD MAX_CDS[3];
    int CDsize = (sizeof(MAX_CDS) / sizeof(MAX_CDS[0]));
    ifstream CDfile("mystock.txt");
    string data;
    int yeardata;
    double pricedata;
    int i;

    for (i = 0; i < 4; i++) {
        getline(CDfile, data);
        MAX_CDS[i].setArtist(data);

        getline(CDfile, data);
        MAX_CDS[i].setTitle(data);

        getline(CDfile, data);
        stringstream yearstream(data);
        yearstream >> yeardata;
        MAX_CDS[i].setYear(yeardata);

        getline(CDfile, data);
        stringstream pricestream(data);
        pricestream >> pricedata;
        MAX_CDS[i].setPrice(pricedata);
    }

    CDfile.close();

    // testing
    cout << MAX_CDS[3].getArtist() << endl; // error !!!
    cout << MAX_CDS[3].getTitle() << endl;
    cout << MAX_CDS[3].getYear() << endl;
    cout << MAX_CDS[3].getPrice() << endl;

    return 0;
}

// constructors implementation
CD::CD() {}

CD::CD(string artist, string title, int year, double price) {
    this->artist = artist;
    this->title = title;
    this->year = year;
    this->price = price;
}
}

1 个答案:

答案 0 :(得分:2)

MAX_CDS中只有3个项目的空间(请参阅CD MAX_CDS[3];),但您引用了错误中的第4个项目。

MAX_CDS[3] // Actually represents the 4th item

计数从C ++中的0开始。

因此,要引用第3项(在您的情况下为 last 项目),请使用MAX_CDS[2]MAX_CDS[CDSize-1]

cout << MAX_CDS[CDSize-1].getArtist() << endl;
cout << MAX_CDS[CDSize-1].getTitle() << endl;
cout << MAX_CDS[CDSize-1].getYear() << endl;
cout << MAX_CDS[CDSize-1].getPrice() << endl;

重读你的问题,你可能想要更多的物品!

CD MAX_CDS[4]; // Now you have 4 items available: indexed 0, 1, 2, and 3