Sign in to follow this  

Question about how to do an exercise in a book?

This topic is 4733 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

The exercise is as follows: "Write a program to count how many times each distinct word appears in its input." This exercise came out of Accelerated C++, chapter three. In this chapter, vectors are covered along with the while (cin >> x) loop. Im assuming that you have to use these two things, but i can't think of a way to do it. Im thinking that you store each string in the vector by using the .push_back(x) member function. But then i dont know what to do from then. I dont think the chapter covered how to do this. Any help on this problem is appreciated. Thanks.

Share this post


Link to post
Share on other sites

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
vector<string> word;
vector<string>::const_iterator cIter;
vector<string>::const_iterator pIter;

int count;

string input;

while (cin >> input)
{
word.push_back(input);
}

for (cIter = word.begin(); cIter != word.end(); ++cIter)
{
count = 0;

for (pIter = word.begin(); pIter != word.end(); ++pIter)
{
if (*cIter == *pIter)
++count;
}

cout << *cIter << " appears " << count << " time.\n";
}

return 0;
}



You can do this...

Share this post


Link to post
Share on other sites

This topic is 4733 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this