【发布时间】: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。不确定这是否会破坏代码(预计无法编译)