2
尝试使用ifstream读取文件。我得到以下错误: 向量下标超出范围 这种情况发生,直到我达到打开文件的结束语句,删除它不会导致异常。 以下是一些示例代码:关闭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'。不知道这是否会破坏代码(期望不能编译) – xinaiz