Write a program that prints the number of words found in a text file. Words are
ID: 3634305 • Letter: W
Question
Write a program that prints the number of words found in a text file. Words are defined as sequences of characters separated by white space. (Hint: white space is defined as in the fscanf function when reading a string). The program should prompt the user for the name of the file to be analyzed. It is assumed that the words in the text file are all shorter than 256 characters, and that the name of the text file is shorter than 64 characters.
The program should reproduce the following format:
Enter the file name: myfile.txt
myfile.txt contains 167 words.
Explanation / Answer
#include #include #include #include using namespace std; string getInputFileName(); // a function to prompt for the complete file name int numCharsInFile( ifstream &in, int &numLines ); // a function to count the // number of characters and // lines in a text file int numWordsInFile( ifstream &in, int &numWords ); // a function to count words in file void main () { int nLines, // number of lines in the text file nChars, // number of characters in the text file avgCharsPerLine, // average number of characters per line nWords; // number of words in the text file ifstream inFile; // handle for the input text file string fileName; // complete file name including the path fileName = getInputFileName(); // prompt and obtain the full file name inFile.open(fileName.c_str()); // try to open the file if( !inFile.is_open() ) // test for unsuccessfull file opening { cerrRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.