tags:

views:

121

answers:

5

I'm prompting the user for a filename, if they enter a valid filename the first time, it works. However, if its invalid the first time, every other check fails. How would I fix this? Also, let's say they just specify a directory, how would I get the names of all the text files and how many there are?

int main() {

    ifstream inFile;
    int result;
    string filename;

    cout << "If the executable is not in the same directory as the\nfile, then a directory needs to be provided\n\n";
    while (true) {
     cout << "Enter the file name:  ";
     getline(cin, filename);
     inFile.open(filename.c_str(), ios::in);

     if (!inFile)
      cout << "\n**File failed to open**\n\n";
     else break;
    }

    result = countLOC(inFile);
    cout << "\nThere are " << result << " lines of code in \"" << filename << "\"\n\n";

    inFile.close();
    return 0;
}
+4  A: 

Call clear to reset the state before the call to open.

lothar
+2  A: 

This is because the error bits in the object 'inFile' have been set.
You need to reset the error bits before you do anything else.

if (!inFile)
{
    cout << "\n**File failed to open**\n\n";
    inFile.clear();
}
else break;
Martin York
A: 

You don't really need to make use of the error flags etc., you can just call the inFile.is_open() function for checking. You will not need to use inFile.clear() either.

Dunya Degirmenci
A: 

Yes do a clear

if the user provides a directory you need to do FindFirst and FindNext

msdn.microsoft.com/en-us/library/zyzxfzac(VS.71).aspx

and process all files that way.

AppDeveloper
A: 

Clear it. Also, you don't need the break in your loop, I'd suggest this instead:

do {
    if (infile.fail())
       cout << "\n**File failed to open**\n\n";
    infile.clear()
    cout << "Enter the file name:  ";
    getline(cin, filename);
    inFile.open(filename.c_str(), ios::in);
} while(!infile)
workmad3