while(getline(myReadFile, temp, ':')) 执行一次迭代太多导致向量越界
while(getline(myReadFile, temp, ':')) executing one iteration too many causing out of bounds on vector
我有一个关于 std::readline(istream, string, delimiter) 的问题。我正在尝试读取文件并将数据存储在结构中并将其添加到地图中。我已经开始工作了。但是,我的 while 循环迭代了一个循环太多,导致我的向量中没有存储任何数据,这导致断言越界失败。
我已经阅读了 readline 上的每个堆栈溢出问题,none 似乎让我知道为什么会出现这种行为。也许这里有人可以启发我。
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();
感谢您的帮助
目前的代码应该在第一次迭代时中断。
假设你以一个空的 vection 开始,你在 tmp
中读取了文件的第一行,没问题。然后你 push_back tmp 进入你的向量,仍然没问题。向量恰好包含索引 0 的一个元素。
但在下一行,您尝试使用仅包含一个元素的向量中索引 1、2 和 3 的元素 => 保证索引超出范围异常。
我有一个关于 std::readline(istream, string, delimiter) 的问题。我正在尝试读取文件并将数据存储在结构中并将其添加到地图中。我已经开始工作了。但是,我的 while 循环迭代了一个循环太多,导致我的向量中没有存储任何数据,这导致断言越界失败。
我已经阅读了 readline 上的每个堆栈溢出问题,none 似乎让我知道为什么会出现这种行为。也许这里有人可以启发我。
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();
感谢您的帮助
目前的代码应该在第一次迭代时中断。
假设你以一个空的 vection 开始,你在 tmp
中读取了文件的第一行,没问题。然后你 push_back tmp 进入你的向量,仍然没问题。向量恰好包含索引 0 的一个元素。
但在下一行,您尝试使用仅包含一个元素的向量中索引 1、2 和 3 的元素 => 保证索引超出范围异常。