-2

这是我的文本文件中的一行:

1 1 10 20 20 50 donut frank 0.75 1.50 100.00

每个单独的类变量由空格分隔。我的代码永远不会进入 while 循环。有人可以解释发生了什么以及我该如何解决吗?

void load_inventory(vector<Item*> &items, string filename){
  ifstream infile;
  infile.open(filename.c_str());
  istringstream stin;
  string line;
  cout << "WORKS" << endl;
  if(!infile){
    cout << "there was an error opening the file" << endl;
    return;
  }

  while(!infile.eof()){
    cout << "INSIDE THE LOOP" << endl;
    Item* item = new Item();
    getline(infile, line);
    stin.str(line);
    item->setMonth(stin);
    item->setId(stin);
    item->setNum(stin);
    item->setDesired(stin);
    item->setLife(stin);
    item->setVolume(stin);
    item->setName(stin);
    item->setSupplier(stin);
    item->setCost(stin);
    item->setPrice(stin);
    item->setSales(stin);
    items.push_back(item);
    stin.clear();
    stin.seekg(0);
  }
}
4

1 回答 1

0

The problem was that you were passing the string stream to your Item functions rather than the actual value. Try this:

std::ifstream infile(filename);
std::string line;

int month, id, num, desired, life, volume;
std::string name, supplier;
float cost, price, sales;

while (std::getline(infile, line))
{
    std::istringstream iss(line);
    if (
        iss >> month >> id >> num >> desired >> life >> volume
            >> name >> supplier >> cost >> price >> sales)
    {
        Item* item = new Item();

//    vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
        item->setMonth(month);
        item->setId(id);
        item->setNum(num);
        item->setDesired(desired);
        item->setLife(life);
        item->setVolume(volume);
        item->setName(name);
        item->setSupplier(supplier);
        item->setCost(cost);
        item->setPrice(price);
        item->setSales(sales);
//    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

        items.push_back(item);
    }
} 

Note that you should be using a container that manages the memory for you, like std::unique_ptr. Also, the constructor to your Item class should take parameters for the values.

于 2013-10-25T19:16:44.797 回答