2016-03-28 73 views
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; 
} 

任何人都可以在这里解释我的错误吗?

+1

行的事这甚至编译?你在'int main()'之后忘了'{''。当添加并且'ifile.close()'被取消注释时,在我的情况下不会引发任何异常(在myswardwords.txt中添加一些随机文本)我正在使用启用了C++ 14的GCC 4.9.3。编辑:另外,你不包括'iostream',但使用'std :: cerr'。不知道这是否会破坏代码(期望不能编译) – xinaiz

回答

0

你已经发布的代码有一些编译时的问题:

  1. 你不#include <iostream>
  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>() };