Test Code for file not found in file I/O situations
Hello,
I'm in an Intro to Programming class with C++. I have this small project based on using c_str for I/O with files.
Can someone help me with my attempt to check for whether the file exists and get it to work so the program doesnt' just close when a file that doesn't exist gets typed in? I'm using DevC++ so have to use system("PAUSE"); in the code.
Here's the code:
//******************       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") 
    {
       
        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;
}
Thanks
Kris






0 Comments:
Post a Comment
<< Home