Count Words in a Text File – Computer Sir Ki Class

Login


Lost your password?

Don't have an account ?
Register (It's FREE) ×
  

Login
[lwa]



Solved Problem #CPP#5034    siteicon   siteicon  

Problem Statement - Count Words in a Text File

Write a function to count and return the number of words present in the filename passed to it as an argument. Assume that each word is separated by a single space and their is no space in the
beginning and end of the file.

Also demonstrate the use of this function in the main routine assuming a file NOTES.TXT that contains the following text.

This is first line
This is second line
This is third line

Solution

TC++ #5034

 

Run Output

No. of words in given file = 12

#include <fstream.h> //This include file is required to support ifstream class

int countwords(char fname[]) {
Passing fname as character array that would contain user given filename. Returning int data type that would contain the count of words.

ifstream ipfile(fname,ios::in); //Opening the filestream in input mode for the filename passed as function argument.

int c=0; //This would contain the word count thus initialised to 0 in the beginning.

if(!ipfile) return -1;
This line checks for file presence or openability so that errors can be avoided later. return value is set as -1 as normal return value when word is found or not found will be 0 or greatet.

while(!ipfile.eof()) { //This loop runs until end of file is not reached.

char word[50]=””;  //This char array would store the word collected from the file, This assumes that no word is larger than 49 characters assuming c++ puts null character at the end. This is most practical for any English word.

ipfile>>word; //Using the property of >> file extraction operator we collect a word from the file as this operator is able to collect data till first space it finds.

if(strlen(word)>0) c++; //If some word is actually present then its string length would be more than 0 and then only variable c, the word count is increased.
}
ipfile.close();  //File is closed
return c;  //word count is returned. if there is no word in file 0 would be returned.
}

int main() {
int c=countwords(“NOTES.TXT”); //The filename is passed to the given function and then the wordcount will come in variable c.
if(c==-1) {cout<<“Unable to open file”<<endl; return 1;} //if -1 is returned then file was not possible to open.
cout<<“No. of words in given file = “<<c<<endl; //Word count is printed.
return 0;
}

Notes

  • This code can be tested on your local system only once a file with given content is created with its name as NOTES.TXT
  • It is always a good practice to check if the file has been opened properly. It will not open properly in many cases. One can reach the OS by returning an error to the operating system.
  • For DOS testing with TurboC environment, learners are advised to keep the input file in the BIN directory are the turboc program runs from there.

Common Errors

  • Programmers often increase word count without checking for string length of collected word. In that case extra word count will return.
  • If we break the while loop by putting extra eof() check before counting, then a file containing single word  will give 0 word count. for e.g. if the while loop is written as follows.
    char word[50]=””;
    while(!ipfile.eof())
    {
    ipfile>>word;
    if(ipfile.eof()) break;
    c++;
    }


Share

CSKC| Created: 25-Nov-2018 | Updated: 29-Nov-2018|






×
Introductory Sessions Beginning to Program Tokens Keyword and Identifiers Data Types Variables and Constants Operators Simple User Input Building Expressions and Formulas Simple Real World Problems Simple If and If Else Multiple-Nested-Ladder of If Else Switch case selection Simple Loops Tricks in Loops - break continue scope Loop Applications - Handling numerals Series printing loops Nested Loops Pattern printing loops Number Varieties and Crunches String Handling (Null Terminated) Strings - string class type Functions (Built-in) Functions - user defined Functions Reference Passing/Returning Arrays Concepts and 1-D Arrays Array Data Management Two dimensional arrays and Matrices Structures Basics Structures passing/returning 2D Array Memory Addressing Display Using IO Manipulation Display Using C Formatting Tricks User Defined Data Types Enumerated Types Preprocessor Directives And Macros Exception Handling Programming Paradigms and OOPs Advantages Abstraction and Encapsulation Polymorphism Inheritance Function Overloading Concepts Function Overloading Varieties Function Overloading Special Cases Defining Classes Creating and Using Class Objects Class Members Accessibility Class Function Types Inline Functions Constant Functions Nesting of Functions Class Members Scope Resolution Static Members in a Class Array of Objects Constructor Concepts Default Constructor Parameterized Constructor Copy Constructor Constructor Overloading Destructors Inheritance Fundamentals Public Derivations Private and Protected Derivations Multiple Inheritance Multi-Level Inheritance Class Nesting Data File Concepts Handling Text Files Handling Binary Files Pointer Concepts Pointer and Arrays Pointers and Functions Object Pointers This Pointer Linked Lists Stacks Queues


Back