Thursday, July 9, 2009

How to implement count words in c++?

i have a program which is reading a file and display it,so i dont know how to count a words in a file.plz i need your help.





here is a code below:





#include %26lt;fstream.h%26gt;


#include %26lt;stdio.h%26gt;


#include %26lt;string.h%26gt;








class task2


{





public:


void readfile();


//void displayfile();


//void sortalphabetical();


//int count();


};





void task2::readfile()


{


char a[100][80];


char str[200];


int i=0;


fstream file("me1.cpp",ios::in);


file.unsetf(ios::skipws);





while(!file.eof())


{


file.getline(str,200);


strcpy(a[i],str);


i++;


}





file.close();


for(int j=0; j%26lt;i; j++)


cout%26lt;%26lt;a[j]%26lt;%26lt;endl;





}








void main()


{


task2 me;


me.readfile();





getchar();


}





so how to implement count a word.......

How to implement count words in c++?
you need to scan through each char and check for Spaces,Commas,Semicolons,Tabs,Backslash,... etc.





The count of words is eactly equal to above chars which are not in continues order.


eg.


Hello here is double space then three comma ,,,then a commanand word.





So the total words are 12 the logic is





Start





read char


If alphabet then


   if not Wordstarted then


   then word started = true


   word=word+1


  end if


else


  wordstarted=false


end if





goto start
Reply:The trick is to not count the words, but to count the things that separate words like spaces, tabs, punctuation etc.





Rawlyn.


No comments:

Post a Comment