Counting the Number of Characters, Words, and Lines in a Text File - C++ File Stream

C++ examples for File Stream:Text File

Description

Counting the Number of Characters, Words, and Lines in a Text File

Demo Code

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cctype>

using namespace std;

void countStuff(istream& in, int& chars, int& words, int& lines) {

   char cur = '\0';
   char last = '\0';
   chars = words = lines = 0;/*ww w. j  av  a 2  s.co  m*/

   while (in.get(cur)) {
      if (cur == '\n' || (cur == '\f' && last == '\r'))
         lines++;
      else
        chars++;
      if (!std::isalnum(cur) && std::isalnum(last)) // This is the end of a word

         words++;
      last = cur;
   }
   if (chars > 0) {               // Adjust word and line counts for special case
      if (std::isalnum(last))
         words++;
      lines++;
   }
}

int main(int argc, char** argv) {
   ifstream in("main.cpp");

   if (!in)
      exit(EXIT_FAILURE);

   int c, w, l;

   countStuff(in, c, w, l);
   cout << "chars: " << c << '\n';
   cout << "words: " << w << '\n';
   cout << "lines: " << l << '\n';
}

Result


Related Tutorials