while(getline(myReadFile, temp, ':')) 执行一次迭代太多导致向量越界

while(getline(myReadFile, temp, ':')) executing one iteration too many causing out of bounds on vector

本文关键字:太多 迭代 越界 一次 向量 执行 temp myReadFile while getline      更新时间:2023-10-16

我有一个关于std::readline(istream,string,delimiter)的问题。我正在尝试读入一个文件,将数据存储在一个结构中,并将其添加到映射中。我已经开始工作了。然而,我的while循环迭代一个循环太多,导致我的向量中没有存储任何数据,从而导致越界断言失败。

我已经阅读了readline上的每个堆栈溢出问题,似乎没有一个问题让我知道为什么会发生这种行为。也许这里有人能启发我。

if (myReadFile.is_open()) {
while(getline(myReadFile, temp, ':')){//loops through and splits the line one delimiter at a time
stringVector.push_back(temp);//add to vector
ItemInfo tempItem = ItemInfo(stringVector[1], stod(stringVector[2]), stod(stringVector[3]));//create the struct
catalog.insert(pair<string,ItemInfo>(stringVector[0], tempItem));//add to map
stringVector.clear();
}
}
myReadFile.close();

感谢的帮助

当前代码应该在第一次迭代时中断。

假设您使用一个空向量开始,那么就可以读取tmp中文件的第一行。然后将tmp推回到向量中,仍然可以。矢量正好包含索引0的一个元素。

但在下一行中,您将尝试使用向量中索引为1、2和3的元素,该向量只包含一个元素=>索引超出限制异常保证。