User invocation for file or directory name

I ask the user for the file name, if he enters a valid file name for the first time, it works. However, if it is invalid the first time, every other check fails. How can I fix this? Also, let's say they just indicate a directory, how can I get the names of all text files and how many are there?

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;
}

      

+1


a source to share


5 answers


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



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

      

+3


a source


Call clear to reset the state before opening the call.



+3


a source


You don't really need to use error flags etc., you can just call the inFile.is_open () function to check. You also don't need to use inFile.clear ().

0


a source


Yes, make it clear

if user provides a directory you need FindFirst and FindNext

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

and handle all files that way.

0


a source


Clean it up. Also, you don't need a break in your loop, I would 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)

      

0


a source







All Articles