gpt4 book ai didi

c++ - 获取 out_of_range : vector error for c++ but can't figure out why

转载 作者:行者123 更新时间:2023-11-30 01:19:48 25 4
gpt4 key购买 nike

这是我的代码:

StockAccount::StockAccount() {
vector<string> temp;
string line;
std::ifstream stockfile("Results.txt");
if (stockfile.is_open()) {
while (stockfile.good()) {


getline(stockfile, line);
istringstream ss(line);
string token;
while (std::getline(ss, token, ',')) {
temp.push_back(token);
}

addStock(temp.at(0), temp.at(1), temp.at(2));

temp.clear();

}
stockfile.close();
} else {
cout << "Unable to open file" << std::endl << std::endl;
}

}

我知道它效率不高,这就是我要解决的问题。它应该做的是:

  1. 逐行阅读该文件。
  2. 解析每一行并用逗号分隔。
  3. 获取这 3 个值并在方法中使用它。

我正在使用该 vector temp 来存储值,将它们添加到函数中,然后将其清除,以便它可以为空并再次用于存储下一个值......等等。

我尝试在 temp.clear() 之前打印出每个值,它们都打印出来,然后我得到了错误。所以我知道 temp.clear() 是问题所在。也许我使用了错误的方法,或者有更好的方法。

我想尝试,如果可能的话不使用 boost。

这是我遇到的错误:

libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: vector

Results.txt 是一个看起来像的文件。

goog,525,0MSFT,34,10

等等。

最佳答案

while (stockfile.good()) 是错误的,会导致您阅读额外的、不存在的一行。

那是因为您在尝试读取新行之前检查流有效性;如果没有要读取的新行,只有在 调用 getline 之后,此条件才会评估为 false 但到那时为时已晚您正在尝试处理这条不存在的线路。

那条不存在的行上没有三个标记,但您没有对标记化执行错误检查,也没有验证 vector temp 的大小。

因此,当您尝试访问这三个不存在的 vector 元素时,会抛出异常。

你的循环应该是这样的:

while (getline(stockfile, line)) {
istringstream ss(line);
string token;
// ...
}

请注意我是如何直接检查循环条件是否成功的,如果实际的 getline 失败,这将阻止执行循环体。

关于c++ - 获取 out_of_range : vector error for c++ but can't figure out why,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20406242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com