Monday, May 24, 2010

What c++ code is required for counting the number of occurences of a word in a text file?

Count the no of times the word "the" occurs independently in a text file.I want a c++ coding for it...

What c++ code is required for counting the number of occurences of a word in a text file?
The straightforward code as requested is:





void count_the()


{


int cnt = 0; // Counter Declaration


fstream fil;


fil.open("Filename.txt", ios::in);


char str[80];


while(fil.getline(str, 80)) // Checks for end of file, reads each line


{


fil%26gt;%26gt; str; // For word by word extraction


if (strcmp("the", str) == 0) // Comparison


cnt++;


}


cout%26lt;%26lt; "The no. of times the word 'the' appears is: "%26lt;%26lt; cnt;


} // Enjoy!
Reply:Dunno. Go ahead and code it up and show us.
Reply:Use AWK for text file procesing files, then u may use a AWK 2 C++ translator.
Reply:I'm gonna tell you how to do it.


Read the file into an array. then with a for statment, go through the array one by one. compare each array element with the text you want to find with if statement(e.g: if(array[i] == "my text") inside the if, you will have an integer that everytime you go inside the if (i.e you find that text) you add one to it (i++)


when the for statment goes to the end of the array you will have a nice integer that tells you how many time that text was repeated in the file.


of course this works in the case you have text in different lines in the file so you read each line in one element of array.


And if its not in the line, you read the whole file in one string, then split it by space, and put it inside an array, and then the for loop and if statment will do the job.


If you use C# it's gonna be a lot easier ;)


hope it helps


No comments:

Post a Comment