Word Counter Help Please!!!!

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.
This &%file ________________ should!!,...



have exactly 7 words.


Note: __________ represents spaces.

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
#include <iostream>
#include <fstream>            // For file I/O
using namespace 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;
}
Last edited on
if whitespace are the only criterion use operator>>:
1
2
3
4
5
6
  count = 0;                       // Initialize counter
  std::string word;
  while (inFile >> word)                   // While input succeeds . . .
  {
      count++;                // Increment counter
  }
Last edited on
That solved my issue thank you!
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;
   }
   else if ( !IsWord )
   {
      IsWprd = true;
      count++;
   }
} 



Topic archived. No new replies allowed.