Reputation: 489
I have the following code:
string promptPlayerForFile(ifstream &infile, string prompt) {
while (true) {
string filename;
cout << prompt;
getline(cin, filename);
infile.open(filename.c_str());
if (!infile.fail()) return filename;
infile.clear();
cout << "Unable to open that file. Try again." << endl;
}
}
The function works as expected: you enter file names until you give a correct one, in which case it associates a stream with the file and returns the filename string.
I then tried commenting out the line infile.clear()
to see what happens. (I read that it needs to be included after a failure has occurred in order to reset the relevant bits of the stream.)
However, after commenting this out, the function behaves as before. If I first give a wrong filename and then a correct one it works, so somehow the failure bits get reset even without that line. Is then infile.clear()
necessary and what are its appropriate uses?
Upvotes: 0
Views: 656
Reputation: 206637
If you are using C++11 or higher, you don't need to call infile.clear();
. If open()
is successful, then clear()
is called.
If you are using a pre-C++11 compiler, it is necessary to call infile.clear()
. The language does not guarantee that the failbit(s) are cleared when open()
is successful.
See https://en.cppreference.com/w/cpp/io/basic_ifstream/open for details about the call to clear()
.
Upvotes: 5
Reputation: 35154
the infile.clear()
is relevant if and only if you want to continue to interact with the stream (e.g. read from it). If your program ends anyway, you dont't have to clear the error flags.
Upvotes: 0