I have a very simple code and the functionality of it is to type in the name of the file from which the program will read data. Since the file might not be correct due to mistyping, the console will continue to ask the user to type in the name if the previous name is invalid.
The issue is, while the first do-while loop works fine, the program will skip the second while loop if the name of the file is not correctly typed in for the first time in the first loop. However, if the name of the file is typed in correctly, everything works fine.
I wonder why the program behaves like this.
Thanks for your help and your time!
#include<iostream>
#include<fstream>
using namespace std;
int main() {
string context;
int step=0,i=0;
ifstream fin;
do {
string filename;
cout << endl << "please type in the name of input file" << endl;
cin >> filename;
string filepath = "files/" + filename;
cout << filepath << endl;
fin.open( filepath.c_str() );
} while( !fin.is_open() );
while (getline(fin, context)){
cout << context << endl;
cout << "hello" << endl;
}
fin.close();
return 0;
}
I think that the state of “fin” might be tainted after the first try.
Why dont you try calling fin.clear() before the call to fin.open().