Problem finding the ratio of frequency of a word to total no of words in a text file in c -
#include<conio.h> #include<stdio.h> #include<iostream.h> #define null 0 int main() { char name[20],c; int nw=0; int j=0; int t=0; char s[] = "newas"; // find frequency of word in abc.txt char p[5]; file *fpt; //printf("enter name of file checked:- "); //gets(name); fpt=fopen("abc.txt","r"); if (fpt==null) { printf("error - can/'t open file %s",name); getch(); exit(0); } else { while ((c=getc(fpt))!=eof) { switch(1) { case 1: if (c==' ') { point: while((c=getc(fpt))==' '); if (c!=' ') nw=nw+1; // if(c==' ') // nw--; if(j < 5) p[j++] = c; printf("\n %c ",p[j]); if(j == 5) { if(p == s) { t++; j = 0; } } } if(c==' ') { j = 0; goto point; } } } } printf("\n no. of words %d. ",nw); printf("\n freq of words %s %d. ",s,t); getch(); }
the code above code giving right answer total number of words not giving right value of frequency of particular word [s in given code], please comment on this, how calculate frequency of particular word in text file.
as including iostream.h, guess supposed form of c++, not c. if so, how word frequencies:
#include <iostream> #include <map> #include <string> #include <fstream> using namespace std; typedef map <string, int> freqmap; int main() { freqmap frequencies; ifstream ifs( "words.txt" ); string word; while( ifs >> word ) { frequencies[ word ] += 1; } ( freqmap::const_iterator = frequencies.begin(); != frequencies.end(); ++it ) { cout << it->first << " " << it->second << "\n"; } }
Comments
Post a Comment