Word count for input file: file read with ifstream : File Utility « File « C++






Word count for input file: file read with ifstream

 

#include <iostream>
#include <fstream>
#include <cctype>
using namespace std;

int main(int argc, char *argv[])
{
  if(argc!=2) {
    cout << "Usage: COUNT <input>\n";
    return 1;
  }

  ifstream in(argv[1]);

  if(!in) {
    cout << "Cannot open input file.\n";
    return 1;
  }

  int count=0;
  char ch;

  in >> ch; // find first non-space char

  // after first non-space found, do not skip spaces
  in.unsetf(ios::skipws);

  while(!in.eof()) {
    in >> ch;
    if(isspace(ch)) {
      count++;
      while(isspace(ch) && !in.eof()) 
         in >> ch; // find next word
    }
  }

  cout << "Word count: " << count << '\n';

  in.close();

  return 0;
}


           
         
  








Related examples in the same category

1.Read and display a text file line by line.
2.Display contents of specified file in both ASCII and in hex.
3.Create a file comparision utility.
4.Copy a text file and display number of chars copied.
5.Copy files
6.Copy a file and display number of chars copied.
7.Concatenate files
8.Swap characters in a file.
9.Swap characters in a file with error checking.
10.Copy a file and reverse case of letters.
11.Count letters.
12.Copy a file and reverse case of letters with error checking.
13.Copy and convert tabs to spaces.
14.Search file.