Loop problem? or can't .txt file?

So I am having a loop issue each time I type in a valid file name after telling my program I want to run it again. It says cannot open file and I do not know why.
I have created .txt files named test,test2,test3,test4. So when I type test.txt it reads the file and it will ask for another file name and I will type test2.txt but it fails to read it. Not sure why. Here is my code.
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
38
39
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    int count;// Number of word operators
    char again;
    ifstream inFile;// Data file
    string filename,word;

do
  {

   // Get the filename from the user.
   cout << "Enter the filename or type 'quit' to quit: ";
   cin >> filename;


    inFile.open(filename.c_str());// Attempt to open file
      if(!inFile)
      {
        // If file wouldn't open, print message
        cout << "Can't open input file" << endl;

      }
        if(inFile)
        {
        count = 0;// Initialize counter

        while (inFile>>word)// While input succeeds . . .
        {
            count++;
        }
        cout << count << " words operators were found." << endl;
        }
   }while(filename != "quit");
   return 0;
}
Yeah bring these lines at the end of the loop for it to work:

1
2
filename.clear();  //to clear the string in case of anything
inFile.close();  //very important: to close the current file, in order to open another! 


Hope it helps,
Aceix.
Topic archived. No new replies allowed.