Object
Write a program that counts the total number of characters, tabs, spaces and new lines in a file.
(download example8.txt)
Algorithm
- Create an ifstream object inFile to handle input operations on a file.
- Declare character variables ch and fn[30].
- Declare integer variables noc, nob, nol and not.
- Set noc=0, nob=0, nol=0 and not=0.
- Read filename fn (example8.txt in this case).
- Open the file named example8.txt using inFile.open().
- IF the file fails to open,
- Write “Error: Unable to open the file”.
- Exit.
- [End of IF structure.]
- WHILE ch ≠ End of file (i.e., until the end of the file is reached)
- ch = inFile.get().
- noc++.
- IF ch = ‘ ‘
- nob++.
- [End of IF structure.]
- IF ch = ‘\n’
- nol++.
- [End of IF structure.]
- IF ch = ‘\t’
- not++.
- [End of IF structure.]
- [End of WHILE loop.]
- ch = inFile.get().
- Close the file.
- Write “The number of characters = noc, blanks = nob, tabs = not and lines = nol”
- Exit.
Flowchart

C++ Source Code
// program 110
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile;
char ch, fn[30];
int noc = 0, nob = 0, nol = 0, notb = 0;
cout << "Enter file name: ";
cin >> fn;
inFile.open(fn);
if (!inFile.is_open())
{
cout << "Error: Unable to open the file" << endl;
return 1;
}
while ((ch = inFile.get()) != EOF)
{
noc++;
if (ch == ' ')
nob++;
if (ch == '\n')
nol++;
if (ch == '\t')
notb++;
}
inFile.close();
cout << "\nThe file \"" << fn << "\" contains the following:" << endl;
cout << "Number of characters = " << noc << endl;
cout << "Number of blanks = " << nob << endl;
cout << "Number of tabs = " << notb << endl;
cout << "Number of lines = " << nol << endl;
return 0;
}
C Source Code
/*program 110*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fptr;
char ch, fn[30];
int noc=0, nob=0, nol=0, not=0;
printf("Enter file name: ");
scanf("%s", &fn);
fptr = fopen(fn, "r");
if(fptr==NULL)
{
printf("Error: Unable to open the file");
exit(1);
}
while(ch != EOF)
{
ch=fgetc(fptr);
noc++;
if(ch==' ')
nob++;
if(ch=='\n')
nol++;
if(ch=='\t')
not++;
}
fclose(fptr);
printf("\nThe file \"%s\" contains the following: ", fn);
printf("\nNumber of characters = %d", noc);
printf("\nNumber of blanks = %d", nob);
printf("\nNumber of tabs = %d", not);
printf("\nNumber of lines = %d", nol);
return 0;
}
Output
Enter file name: example8.txt
The file “example8.txt” contains the following:
Number of characters = 693
Number of blanks = 111
Number of tabs = 2
Number of lines = 4
