简体   繁体   English

错误:将元素加载到向量中时出现死循环

[英]Error: Infinite-loop when loading elements into vector

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();
}

The .txt file I am reading from contain data structured in this order: 我正在读取的.txt文件包含按以下顺序结构化的数据:

int
string
int double double

The output which is in the last line of the while-loop is repeated as the first itemID within the file. while循环的最后一行中的输出将作为文件中的第一个itemID重复。 The initData stream does not read subsequent entries in the .txt file. initData流不读取.txt文件中的后续条目。

1111
1111
1111
1111
1111
...

Don't use while (!initData.eof()) -- ever. 永远不要使用while (!initData.eof()) It's pretty much a guaranteed bug. 这几乎是有保证的错误。

I'd start with code to read a single SInventor item from the file: 我将从代码开始以从文件中读取单个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;
}

With that in place, it's probably easiest to just do without the rest of the function, and just initialize the vector directly: 将其放置在适当的位置,可能最简单的做法是不使用其余函数,而直接直接初始化向量:

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

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

No loop, no mucked up test for EOF, etc., just a vector initialized from a pair of iterators. 没有循环,没有对EOF进行破坏性测试,等等,只是从一对迭代器初始化的向量。

You can change your while loop to 您可以将while循环更改为

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

or skip whitespace at the end of your while loop 或在while循环结束时跳过空格

    ws(initData);

or define an operator>>(istream&, SInventory &) and just do 或定义一个operator>>(istream&, SInventory &)然后执行

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM