I am writing a simple program to take a user-supplied file, read the contents, and output email addresses found in the file. If the user supplied an invalid path/file name, I want to prompt the user to try again.
Right now, everything works properly if the first file name the user inputs is valid. If it's invalid, the program correctly identifies that and continues to prompt until a valid file name is provided. If the first file name supplied is invalid, the program bypasses the file parsing routine even though it reports a valid file name.
Here's what I have:
fileExists = false;
while (!(fileExists)) {
cout << "Enter name of the input file.\n";
getline(cin, filename);
cout << "\n\n";
//remove any leading white space in filename
while (filename.substr(0, 1) == " ") {
length = filename.length();
length--;
filename = filename.substr(1, length);
}
inFile.open(filename.c_str());
if (inFile.is_open()) {
fileExists = true;
filename = "";
cout << "Enter the name of the output file.\n";
getline(cin, filename);
//remove any leading white space in filename
while (filename.substr(0, 1) == " ") {
length = filename.length();
length--;
filename = filename.substr(1, length);
}
outFile.open(filename.c_str());
while(inFile) {
inFile >> inValue;
if (inValue.find("@") != string::npos) {
outFile << inValue << endl;
}
inValue = ""; //clear inValue so final value doesn't repeat
}
outFile.close();
} else {
cout << "Input file does not exist\n\n";
filename = "";
}
inFile.close();
}
Let's say I have file c:\temp\myfile.dat. If the user enters it correctly the first time on line 5, everything works properly. If they enter c:\temp\myfil.dat the first time it will respond "Input file does not exist" and loop back up to ask for the input file name. If the 2nd time the user enters c:\temp\myfile.dat, the program recognizes that it's a valid file but doesn't enter the while loop starting on line 32 (I sent some output to console in the loop to check).
Any ideas?