This is an assignment for class and my code works, but my teacher was being cleaver and put several spaces in between words so we couldn't count the spaces then just add one to our counter. So then I check for a space and a character for it to count it as a word, but it doesn't work when I have a number then a space. I have spend hours trying to figure this out and I just can't. It also has to ask the user of the file name before it can open it. That I am sure I got but I need help! Here is what I have.
Here is an example of one his files it has to read.
#include <iostream>
#include <fstream> // For file I/O
usingnamespace std;
int main()
{
int count; // Number of word operators
char prevChar; // Last character read
char currChar; // Character read in this iteration
ifstream inFile; // Data file
string filename;
// Get the filename from the user.
cout << "Enter the filename: ";
cin >> filename;
inFile.open(filename.c_str()); // Attempt to open file
if ( !inFile )
{ // If file wouldn't open, print message, terminate program
cout << "Can't open input file" << endl;
return 1;
}
count = 0; // Initialize counter
inFile.get(prevChar); // Initialize previous value
inFile.get(currChar); // Initialize current value
while (inFile) // While input succeeds . . .
{
if (currChar == ' ' && (prevChar != ' ')) //test for words
count++; // Increment counter
prevChar = currChar; // Update previous value to current
inFile.get(currChar); // Get next value
}
cout << count << " words operators were found." << endl;
return 0;
}
If you shall not use operator >> which was suggested by coder777 then you can write the following code by using std::get
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int count = 0;
bool IsWord = false;
char c;
while ( get( c ) )
{
if ( c == ' ' || c == '\t' ) // or std::isblank( c ) can be used instead
{
IsWord = false;
}
elseif ( !IsWord )
{
IsWprd = true;
count++;
}
}