【问题标题】:Error: Infinite-loop when loading elements into vector错误:将元素加载到向量中时出现无限循环
【发布时间】:2012-12-02 21:52:55
【问题描述】:
void initializeVectorFromFile(vector<SInventory> & inven){

        ifstream initData("inventoryData.txt");

    if(!initData){

        cout << "File could not be accessed! Press any key to terminate program...";
        _getch();
        exit(1);

    }

    while(!initData.eof()){

        SInventory item;

        initData >> item.itemID;

        getline(initData,item.itemName);

        initData >> item.pOrdered
                 >> item.menufPrice
                 >> item.sellingPrice;
        item.pInStore = item.pOrdered;
        item.pSold = 0;

        inven.push_back(item);

        cout << item.itemID << endl;

    }

    cout << "File Read Success!" << endl;

    initData.close();
}

我正在读取的 .txt 文件包含按此顺序排列的数据:

int
string
int double double

while 循环最后一行的输出作为文件中的第一个 itemID 重复。 initData 流不会读取 .txt 文件中的后续条目。

1111
1111
1111
1111
1111
...

【问题讨论】:

  • 首先,不要使用while (!whatever_file.eof())
  • 作业标签已弃用,不应在新问题中使用。
  • @JerryCoffin 在以下情况下这是可以接受的用法,为什么我不能在我的示例中使用这种方法,我应该实现什么。谢谢stackoverflow.com/questions/9979894/…
  • @Michael:不,那里也不是真的可以接受——你可能没有注意到这个问题,但如果你仔细检查,你可能会发现你的代码说它又读了一条记录比实际包含的文件。至于该怎么做:请参阅我的答案以了解一种可能性。

标签: c++ data-structures vector infinite-loop


【解决方案1】:

永远不要使用while (!initData.eof())。这几乎是一个有保证的错误。

我将从从文件中读取单个 SInventor 项目的代码开始:

std::istream &operator>>(std::istream &initData, SInventor &item) { 
    initData >> item.itemID;

    getline(initData,item.itemName);

    initData >> item.pOrdered
             >> item.menufPrice
             >> item.sellingPrice;
    item.pInStore = item.pOrdered;
    item.pSold = 0;    
    return initData;
}

有了它,最简单的方法可能是不使用其余的函数,直接初始化向量:

std::ifstream infile("yourfile.txt");

std::vector<SInventor> inven((std::istream_iterator<SInventor>(infile)),
                              std::istream_iterator<SInventor>());

没有循环,没有针对 EOF 的混乱测试等,只是从一对迭代器初始化的向量。

【讨论】:

    【解决方案2】:

    您可以将 while 循环更改为

    SInventory item;
    while(initData >> item.itemID){
        ...
    

    或在 while 循环结束时跳过空格

        ws(initData);
    

    或者定义一个operator&gt;&gt;(istream&amp;, SInventory &amp;) 就可以了

    SInventory item;
    while(initData >> item){
        inven.push_back(item);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-09-24
      • 1970-01-01
      • 2014-02-23
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-06
      相关资源
      最近更新 更多