The output is an infinite loop of “cannot open the file”. what did I do wrong? thanks in advance. (p.s I am trying to test the condition that it cannot open the file and continue processing by getting the next file name from the vector)
#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;
}
Simply enough, you’re not incrementing the iterator in your error case.