You are here:

C++/repetitive file handling

Advertisement


Question
I'm using Dev-C++ 4.9.9.1 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!
--anton

here's the source code:

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

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

Answer
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.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Sam

Expertise

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

Experience

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

©2016 About.com. All rights reserved.