Using the get() we can easily write a program that can count the number of characters in a file. This will be quite similar to the Word Count option available in Ms-Word.
#include "conio.h"
#include " ctype.h" // for character functions
#include "iostream.h"
#include "fstream.h"
void main()
{
clrscr();
ifstream in("file1.txt"); // name of any existing file
int chars=0,caps=0,small=0,num=0,space=0;
char ch;
in.get(ch);
while(in)
{
if(isalpha(ch))
{
chars++;
if(isupper(ch))
caps++;
else if(islower(ch))
small++;
}
else if (isdigit(ch))
num++;
else if(isspace(ch))
space++;
in.get(ch);
}
cout<<"\nStatistics ";
cout<<"\n============";
cout<<"\nTotal Chars : "<<chars;
cout<<"\nCapital Letters : "<<caps;
cout<<"\nSmall Letters : "<<small;
cout<<"\nDigits : "<<num;
cout<<"\nSpaces : "<<space;
in.close();
}
Output
Statistics
==========
Total Chars : 40
Capital Letters : 20
Small Letters : 10
Digits : 5
Spaces : 5
#include "conio.h"
#include " ctype.h" // for character functions
#include "iostream.h"
#include "fstream.h"
void main()
{
clrscr();
ifstream in("file1.txt"); // name of any existing file
int chars=0,caps=0,small=0,num=0,space=0;
char ch;
in.get(ch);
while(in)
{
if(isalpha(ch))
{
chars++;
if(isupper(ch))
caps++;
else if(islower(ch))
small++;
}
else if (isdigit(ch))
num++;
else if(isspace(ch))
space++;
in.get(ch);
}
cout<<"\nStatistics ";
cout<<"\n============";
cout<<"\nTotal Chars : "<<chars;
cout<<"\nCapital Letters : "<<caps;
cout<<"\nSmall Letters : "<<small;
cout<<"\nDigits : "<<num;
cout<<"\nSpaces : "<<space;
in.close();
}
Output
Statistics
==========
Total Chars : 40
Capital Letters : 20
Small Letters : 10
Digits : 5
Spaces : 5
The above code will first open the file in read mode and start reading the file one char at a time using the "get()". The read char will be checked to see whether it is a capital or small letter, a digit or a space. Wehave declared different counter variables to count each type of char, for example the variable "caps" will count the capital letters while "small" is used to check small letters. To check a character, the character functions "isupper()","islower()" have been used. These are boolean functions and return their value in true/false. We can also use manual comparison statements like "if(ch>='A' && ch<='Z') etc.
0 comments:
Post a Comment