You are here:

C++/repetitive file handling


I'm using Dev-C++ 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, 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:

#include <iostream>
#include <fstream>
using namespace std;

int main ()
   char ch, filename[30], decision;
   int count;
   fstream file;
       count = 0;
       cout << "Enter filename: ";
       cin >> filename; (filename, ios::in);
       file.unsetf (ios::skipws);
       while (1)
         file >> ch;
         if (
         cout << "[END]";
         cout << ch;
         if (ch=='a')
       } // while
       cout << endl << "Number of a's in document: " << count;
       cout << endl << endl << "Run again (y/n)? ";
       cin >> decision;
   } while (decision=='y');
   return 0;

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 ' (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.


All Answers

Answers by Expert:

Ask Experts




You may ask me about simple to complicated C/C++ programming methods/style and most like questions about network programming in C++.


I'm a professional programer in C++ and network/internet programming.

©2016 All rights reserved.