Count words, lines, spaces, and punctuation in char array - C++ Data Type

C++ examples for Data Type:char array

Description

Count words, lines, spaces, and punctuation in char array

Demo Code

#include <iostream>
#include <cctype>
using namespace std;
// A structure to hold the word-count statistics.
struct wc {/*from   w w  w .  j av  a2  s .c o m*/
   int words;
   int spaces;
   int punct;
   int lines;
   wc() {
      words = punct = spaces = lines = 0;
   }
};
wc wordcount(const char *str);
int main() {
   const char *test = "test test this is a test"
   "test test this is a test,\nC++ "
   "test test this is a test "
   "test test this is a test.\n.";
   cout << "Given: " << "\n\n";
   cout << test << endl;
   wc wcd = wordcount(test);
   cout << "\nWords: " << wcd.words << endl;
   cout << "Spaces: " << wcd.spaces << endl;
   cout << "Lines: " << wcd.lines << endl;
   cout << "Punctuation: " << wcd.punct << endl;
   return 0;
}
wc wordcount(const char *str) {
   wc data;
   if(*str)
      ++data.lines;
   while(*str) {
      if(isalpha(*str)) {
         while(isalpha(*str) || *str == '\'') {
            if(*str == '\'') ++data.punct;
            ++str;
         }
         data.words++;
      }
      else {
         if(ispunct(*str)) 
            ++data.punct;
         else if(isspace(*str)) {
            ++data.spaces;
            if(*str == '\n' && *(str+1))
               ++data.lines;
         }
         ++str;
      }
   }
   return data;
}

Related Tutorials