Having issues with file verification loop

So, when I run this, it verifies the file correctly the first time. If I type 'bob.txt' it does the following stuff which I omitted here for simplicity. If I type 'bob', it does the correct process. This is all assuming I have a file called 'bob.txt' in the directory. Now, when I type 'asdf' or 'asdf.txt', it turns back a 'file not found' as it should. However, every reattempt to type 'bob' or 'bob.txt' returns file not found. I put in a 'cout << fileName' to see what filename is being returned and it is always correct. It's just not processing properly. Any thoughts?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
 void customCity()
 {
    string fileName = "file", suffix  = ".txt";
    ifstream locFile;
    int found, retry = 1;
 
    bool fileValid = false;
 
    while (!fileValid)
    {
        cout << "Enter filename:  ";
        getline(cin,fileName);
        found=fileName.find(".txt");
 
        if (found == string::npos)
            fileName += suffix;
 
        locFile.open(fileName.c_str());
        cout << fileName << endl;
 
        if (!locFile)
        {
            if (retry >= 3)
            {
                cout << "ERROR: Too many attempts. Program will now shut      down/n/n";
                exit(1);
            }
            cout << "File not found.";
            retry += 1;
        }
        else if (locFile)
        {
            fileValid = true;
            continue;
        }
    }
}
I figured it out!!! I AM SO PROUD OF ME!!! Sorry for the caps sentence but I ROCK!!!

In case anyone finds this particular problem of interest, the issue was that I wasn't clearing my string. It was carrying over the previous string and not clearing it between loops. So the first time it was getting asdf.txt and the second time it was asdf.txt.bob.txt. At least, that's what I am fairly certain was happening.

Between lines 29 and 30 I added locFile.clear();

Now it works like a charm!
Topic archived. No new replies allowed.