You are here:

C++/c++ progrming

Advertisement


Question
I am a college student taking a introduction class to C++ language.i have no idea about the question.the question is write a program that accepts a passage, analyzes the passage word by word, count the occurrences of each word (regardless of the letter-case used).

Answer
Hello Wang.

I can help you with your question but I'm not sure how much experience you have with C++. My idea is to store all the words and their counts in a map. A map is a standard C++ container that connects keys with values. In your assignment, the keys will be words from the passage, and the values will be the word counts.

The program needs to do the following:
1. get the passage
2. break the passage down into words
3. change each word to lowercase
4. check the map. If the map has the word, increment the word count. If the map doesn't have the word, then insert the word and set the count to 1.

To do this you need to learn about strings and maps. I will give you code to input the passage from the keyboard and break it down into words. Then it is up to you to try finishing the assignment.

Remember, there is always more than one way to solve a problem. If you don't want to learn about maps, you need to create your own data structure to hold words, and their counts. You may have experience with linked lists or binary trees, and you may want to use them instead of a map.

Below is the start of the program. Good luck.
Best regards
Zlatko

#include <iostream>
#include <map>
#include <string>
#include <sstream>

using namespace std;

map<string, int> wordCounts;


int main(void)
{
   /* get the passage */
   cout << "input passage\n";
   string passage;
   getline(cin, passage);

   /*
   break the passage up into words
   by putting it into a stringstream, then using
   getline on the stringstream to get individual words
   */
   stringstream ss(passage);
   string word;
   do
   {
       // get words separated by spaces (' ')
       getline(ss, word, ' ');
       if (ss)
       {
           cout << "Got word " << word << endl;

           /* Now go through each character in the string
           and make it lowercase */


           /* Then check if the word is in the map. If not, insert
           it into the map setting the count to 1, If it is in the map
           then increment the map value by 1.*/

          
       }
   } while(ss);

   /* Print out the words in the map and their counts */

}

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.