c++ - while(getline(myReadFile, temp, ':' )) 执行一次迭代太多导致 vector 越界

标签 c++ readline readfile

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

我已经阅读了 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();

感谢您的帮助

最佳答案

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

假设你从一个空的 vection 开始,你在 tmp 中读取文件的第一行,没问题。然后你 push_back tmp 到你的 vector 中,仍然没问题。 Vector 恰好包含索引 0 的一个元素。

但在下一行,您尝试使用仅包含一个元素的 vector 中索引 1、2 和 3 的元素 => 保证索引超出边界异常。

关于c++ - while(getline(myReadFile, temp, ':' )) 执行一次迭代太多导致 vector 越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29867622/

相关文章:

javascript - Node.js readline.on ('line' , fn()) 看不到换行符

c - 获取程序背后的代码

swift - 如何从 Swift 3 (XCode 8) 中的文本文件中读取数据

c++ - 我如何(干净利落地!)将 std::stringstream 子类化以进行自定义?

javascript - Node.JS Readline 在按退格键时打印新行

perl - 如何在不打印换行符的情况下使用 Term::ReadLine 读取用户输入?

c++ - 将逗号分隔的文本文件读入数组

C++ 指针成员函数与模板赋值与另一个类的成员函数

c++ - asio::buffer 类型用于发送 std::vector 和 std::string

c++ - WebP 无损格式概述