I'm literally losing my mental sanity. I have been attempting this problem for 3 days now, and can't attempt anymore. I cannot figure out what I am doing or eve supposed to be doing, and it's driving me crazy. If someone could explain this to me (my sanity and I) will be forever grateful.
PROBLEM:
Write a program that prints out the number of words in a file of text. We will define a word to be any sequence of non-whitespace characters. So "hi&there...mom" would be considered a single word. Solve this problem by using a string variable into which you input each word as a string. Here are some hints for assignment 4.2. Your program should ask the user for the name of the file to count words in (see Chapter #5 section 5.12 in the Gaddis text titled "Letting the User Specify a Filename" on pgs 300-301 and if you are interested, Chapter #13 section 13.1 - 13.3 in the Gaddis text pgs. 837-861 will provide more advanced File and I/O operations). The program should loop until the user types "quit" for the name of the file.
Turn in your source code, followed by an output which has the user entering these 5 input files: file 1 | file 2 | file 3 | file 4 | file 5
Using notepad, I suggest that you copy/paste the text from each of these five web pages to create five separate text files. Save these files in the same folder in which you have your working copy of your source code.
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
|
// This program counts the number of words in files selected by the user.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main ( )
{
ifstream inputfile;
string filename;
string words;
//Get the filename from the user.
cout << "Enter the filename: ";
cin >> filename;
//Open the input file.
inputfile.open(filename.c_str());
//If the file succesfully opened, process it.
if (inputfile)
{
while (inputfile >> words)
cout << words << endl;
//Clost the file.
inputfile.close();
}
else
{
//Display an error message.
cout << "Error opening the file.\n";
}
return 0;
}
|
My output is reading the words from the file, but I can't even begin to understand the word count part of this.
OUTPUT:
Enter the filename: fileone.txt
This
&%file
should!!,...
have
exactly
7
words.
Program ended with exit code: 0