【问题标题】:Vector subscript out of range after closing ifstream关闭 ifstream 后向量下标超出范围
【发布时间】:2016-03-28 12:54:46
【问题描述】:

尝试使用 ifstream 读取文件。我遇到以下错误: 向量下标超出范围 这种情况会发生,直到我到达打开文件的结束语句,删除它不会导致异常。 下面是一些示例代码:

#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <iterator>
#include <sstream>
#include <iostream>

using namespace std;

int main()
{
    ifstream ifile("myswearwords.txt");

    if (!ifile.is_open())
    {
        cerr << "File not found!\n";
        return false;
    }

    std::vector<std::string> myswearswords;
    std::copy(std::istream_iterator<std::string>(ifile),
        std::istream_iterator<std::string>(),
        std::back_inserter(myswearswords));

//  ifile.close(); -> exception rased, when I reach th ebrakpoint at this point

/// do further work
return 0;
}

谁能解释一下这里的错误?

【问题讨论】:

  • 这还能编译吗?你在int main() 之后忘记了{。添加后,ifile.close() 未注释,在我的情况下不会引发异常(在 myswardwords.txt 中添加了一些随机文本)我使用启用了 c++14 的 GCC 4.9.3。编辑:另外,您不包括iostream,而是使用std::cerr。不确定这是否会破坏代码(预计无法编译)

标签: c++ file stl copy fstream


【解决方案1】:

您发布的代码存在一些编译时问题:

  1. 你没有#include &lt;iostream&gt;
  2. int main() 之后没有立即打开花括号
  3. 你没有声明ifstream ifile

所有这些都更正后,代码运行良好:http://ideone.com/mzOyE2

一旦将数据复制到 myswearswords 中,ifilemyswearswords 之间就没有保留的连接。所以你不应该看到这个错误。

现在显然,如果您甚至能够编译,您还没有向我们展示您所有的实际代码。实际的错误很可能在未显示的代码部分中。

顺便说一句,您可以通过使用vector 构造函数评估器来改进您的代码,而不是随后复制到myswearswords

const vector<string> myswearswords{ istream_iterator<string>(ifile), istream_iterator<string>() };

【讨论】:

    猜你喜欢
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多