|Hi, this is my first post here, so please be understanding and forgiving if I screw up and break some rule or something. I'm having trouble figuring out exactly how to remedy this problem in my C++ program. What I want to do is prompt the user to enter a filename from which data will be read. If the filename entered doesn't match the name of a real/pre-existing file, I want the program to output a message saying so and continue prompting the user to input a filename until a valid filename is entered.|
If I run the program and enter a valid filename on the first go-round, everything works fine and the file is read. However, if I first enter the name of a nonexistent file and on the second try enter the valid filename, the program displays the same error message as if I had entered an invalid filename.
I tried resetting the variable "filename" to an empty string: filename = ""; But I wasn't sure if this was the right way to do it or not, and also it didn't help. Then I tried using cin.clear() and cin.ignore(), but these didn't make a difference either.
Code (I've omitted pieces where they aren't directly relevant):
bool validFile = false;
bool fileRead = false;
while (validFile == false)
cout << "Please enter the name of the file you would like to read from." << endl;
cin >> filename;
cout << "Sorry, the file name you entered is not valid." << endl;
cout << "Please check the name of the input file and try again." << endl;
validFile = false;
(blah blah blah, it reads the file here. the rest of the code isn't relevant)
If it matters, I'm using Microsoft Visual Studio 2008.
Thank you for your help.