C++/repetitive file handling
I'm using Dev-C++ 18.104.22.168 on an Intel P3-1GHz running on Windows 2000 SP3.
I'm trying to make a program that reads a file, count the number of occurrences of a certain character, and to put it inside a loop (in case the user wants to repeat).
Maybe there's some function I have to execute in order to clear the file cache (or something like that). The code reads a file only ONCE. If the do-while loop repeats in whatever case, file.fail() immediately returns 'true' afterwards. [see source code below] I'm stumped. Besides, I already tried looking for sample code in the web, and all the source code I've seen only read a file once, and do not put the code inside a loop.
I'd appreciate any help. Thanks!
here's the source code:
using namespace std;
int main ()
char ch, filename, decision;
count = 0;
cout << "Enter filename: ";
cin >> filename;
file.open (filename, ios::in);
file >> ch;
cout << "[END]";
cout << ch;
} // while
cout << endl << "Number of a's in document: " << count;
cout << endl << endl << "Run again (y/n)? ";
cin >> decision;
} while (decision=='y');
After your file gets FAIL status, you need to refresh it. The easiest way you can do is:
1. remove 'fstream file;'
2. instead of 'file.open (filename, ios::in);' use 'fstream file(filename, ios::in);'
In other words, you define your file variable locally so that it gets refreshed in every loop.