1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
// This program reads the characters, words, and paragraphs
//in a file, the user enters the file and the output is displayed with
//the number of words, characters, and paragraphs
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
//Function Prototypes
void openTheFile(ifstream& fileToBeOpened, string& nameOfFile);
void countCharacters(ifstream &fileToBeOpened, int &numOfChars, int &numOfNewLines);
void testOpenFile(ifstream& fileToBeOpened);
void countWords(ifstream& fileToBeOpened, int wordLengths);
int main()
{
//variable declarations
string nameOfFile, word;
ifstream fileToBeOpened;
int numOfChars = 0, numOfNewLines = 0, wordLengths[] = {}, size = 11;
//functions within the main
openTheFile(fileToBeOpened, nameOfFile);
testOpenFile(fileToBeOpened);
countCharacters(fileToBeOpened, numOfChars, numOfNewLines);
countWords(fileToBeOpened, wordLengths[size]);
return 0;
}
//opens the file the user enters
void openTheFile(ifstream& fileToBeOpened, string& nameOfFile)
{
cout<<"What is the name of the file? ";
cin>>nameOfFile;
fileToBeOpened.open(nameOfFile.c_str());
}
//test to see if the program can open the file, if not the program exits
void testOpenFile(ifstream& fileToBeOpened)
{
if(!fileToBeOpened)
cout<<"Error opening the file!";
//exit(1) the exit causes program to terminate and not display output
}
//counts the number of characters and newlines
void countCharacters(ifstream &fileToBeOpened, int &numOfChars, int &numOfNewLines)
{
char character;
while(character != EOF)
{
character = fileToBeOpened.get();
numOfChars++;
if(character == '\n')
{
numOfNewLines++;
}
}
//cout <<numOfChars <<" " <<numOfNewLines; (testing my function)
}
//counts the number of words in the file
void countWords(ifstream& fileToBeOpened, int wordLengths)
{
string word;
int wordCount = 0;
fileToBeOpened>>word;
while(!fileToBeOpened.eof());
{
fileToBeOpened>>word;
wordCount++;
}
cout << wordCount;
}
//sums the array where the word lengths are stored
/*void sumTheArray (int wordLengths, int size)
{
}
//rewinds the file to the beginning
void rewindFile(ifstream& fileToBeOpened, string& nameOfFile);
{
fileToBeOpened.close();
fileToBeOpened.clear();
fileToBeOpened.open(nameOfFile);
}
*/
//Just need to write a function to display the output.
|