Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

You want to count the number of occurrences of each word in a text file Solution

ID: 3632390 • Letter: Y

Question

You want to count the number of occurrences of each word in a text file

Explanation / Answer

Solution Use operator>>, defined in , to read contiguous chunks of text from the input file, and use a map, defined in , to store each word and its frequency in the file. demonstrates how to do this. Counting word frequencies 1 #include 2 #include 3 #include 4 #include 5 6 typedef std::map StrIntMap; 7 8 void countWords(std::istream& in, StrIntMap& words) { 9 10 std::string s; 11 12 while (in >> s) { 13 ++words[s]; 14 } 15 } 16 17 int main(int argc, char** argv) { 18 19 if (argc < 2) 20 return(EXIT_FAILURE); 21 22 std::ifstream in(argv[1]); 23 24 if (!in) 25 exit(EXIT_FAILURE); 26 27 StrIntMap w; 28 countWords(in, w); 29 30 for (StrIntMap::iterator p = w.begin( ); 31 p != w.end( ); ++p) { 32 std::cout
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote