Monday, October 03, 2005

Re: Test Code for file not found in file I/O situations

I have not tested it but hope its working try it out..
I have just made one change thats in position of if condition where you are checking the existence of file
 
//******************       this line is 70 characters long **********
#include <iostream>
#include <string>
#include <fstream>
#include <cassert>

/*
    Kris Thayer
    10/3/05
    Assignment 5.5

    This program asks to enter the name of a file and then counts the
    words in the file. A word is any sequence of non-whitespace
    characters. When "quit" is entered, the program ends. The files must
    be located in the same folder as the project file. Data is input into
    the program one character at a time and keeps track of current and
    previous characters. Any time the previous character or current character
    is a whitespace character, there's an increment to the count.
*/

using namespace std;

int main()
{
   char currentChar;         // current character read in
   char previousChar;         // last character read
   int wordCount;         // count of sequences of non-whitepace
   string fileName;       // name of file entered
   ifstream inFile;       // declaration of a file variable

   cout << "Type in the filename: ";
   cin >> fileName;

  /* if (!inFile)
   {
      cout << "Please enter a filename that exists: " << endl;
      cin >> fileName;
   }*/
   while (fileName != "quit")
   {
      if (!inFile)
      {
         cout << "Please enter a filename that exists: " << endl;
         cin >> fileName;
     }
     else
     {

       inFile.open(fileName.c_str());
       assert(inFile);

       wordCount = 0;
       inFile.get (previousChar);
       inFile.get (currentChar);

       while (inFile)
       {
           if ((previousChar != ' ' && previousChar != '\n') &&
              (currentChar == ' ' || currentChar == '\n'))

           wordCount++;
           previousChar = currentChar;
           inFile.get (currentChar);
       }

       if (previousChar != ' ' && previousChar != '\n')

           wordCount++;

       cout << "This file contains " << wordCount << " words." << endl;

       inFile.close();
       inFile.clear();

       cout << "\n" << endl;
       cout << "Type in another filename: ";
       cin >> fileName;
     }
}
       system ("pause");

   return 0;
}


 

0 Comments:

Post a Comment

<< Home