2011-11-08 167 views
-1

输出是“无法打开文件”的无限循环。我做错了什么?提前致谢。 (P.S我想测试的条件,它无法打开文件,并通过从向量获取下一个文件名继续处理)clear()进入无限循环

#include <iostream> 
#include <istream> 
#include <fstream> 
#include <vector> 
#include <string> 
using namespace std; 
int main() 
{ 
ifstream input; 
vector<string> files; 
files.push_back("ifile"); 
files.push_back("ifile2"); 
vector<string>::const_iterator iter=files.begin(); 
while (iter!=files.end()) 
{ 
    string s; 
    input.open(iter->c_str()); 
    if (!input) 
    { 
     cerr<<"cannot open the file"<<endl; 
     input.close(); 
     input.clear(); 
     continue; 
    } 
    while(input>>s) 
     cout<<s<<' '<<ends; 
    input.close(); 
    input.clear(); 
    cout<<endl; 
    ++iter; 
} 
return 0; 
} 
+0

清除通常在badbit之后的打开文件上调用以继续处理该文件。试试把它拿出来?不确定它在这里做什么。 –

回答

2

足够简单,你不增加你的错误情况下,迭代器。

+0

谢谢。问题解决了! – ihm

4
if (!input) 
{ 
    cerr<<"cannot open the file"<<endl; 
    input.close(); 
    input.clear(); 
    ++iter; 
    continue; 
} 

您需要在此处增加迭代器。

+0

谢谢!工作。 – ihm

+0

或者可以删除'cerr'后面的所有行。无论如何,下面的输入循环都会被忽略。 - 毕竟你正在关闭一个文件,你无法打开,它不会造成任何伤害。 – visitor

1
  1. ITER = files.begin()
  2. 开始循环
  3. 打开失败
  4. ITER不递增
  5. 转到2

写这可能是更好的办法使用for (;;)循环,迭代器增量发生在第三个子句中,因此continue不会绕过它。

+0

谢谢。它现在正在工作 – ihm