My 3rd project worked the first time!! Made a few simple mistakes (missing a semicolon here and there) and had some issues with pointers which I will discuss in a sec
project requirements:
Quote
For your third project, you are to write a program to create a frequency list
of words in a passage.
A frequency list is a list of the distinct words in the
passage together with a cout of the number of times that word occurs.
The input will be read from stdin [i.e., cin]. The output is to be sent to
stdout [i.e., cout], sorted alphabetically on the words.
I want you, for each word that is read, to convert all the characters to lower
case [so that The and the are counted together] and if the word ends in a
punctuation symbol, to remove it [you may assume that there is at most one
punctuation mark].
You can use a binary tree, sorted on the words, to hold the words and their
counts. If a word is seen again, increment the count.
here is the code:
MAIN:
Code
#include <iostream>
#include "tree.h"
#include <string>
#include <ctype.h>
using namespace std;
int main()
{
string word;
string::iterator it;
int strlen;
tNode *root = NULL;
while (cin >> word)
{
it = word.end()-1;
strlen = word.length();
if (ispunct(word[strlen-1]))
{
word.erase(it);
}
for (int i = 0; i < strlen; i++)
{
word[i] = tolower(word[i]);
}
tAdd(word, root);
}
inOrder(root);
return 0;
}
TREE.CPP
Code
#include "tree.h"
#include <string>
#include <iostream>
using namespace std;
void tAdd(string input, tree & root)
{
if (root == NULL)
{
tNode *node = new(tNode);
node->word = input;
node->counter = 1;
node->left = node->right = NULL;
root = node;
return;
}
if (input == root->word)
{
root->counter++;
return;
}
else if (input < root->word)
{
tAdd(input, root->left);
}
else tAdd(input, root->right);
}
void inOrder(tree root)
{
if (root == NULL)
{
return;
}
inOrder(root->left);
cout << root->word << " has occurred " << root->counter << " time(s)." << endl;
inOrder(root->right);
}
TREE.H
Code
#include <iostream>
#include <string>
using namespace std;
struct tNode
{
string word;
int counter;
tNode *left, *right;
};
typedef tNode *tree;
void tAdd(string word, tree & root);
void inOrder(tree root);
proj. said his main was like 67 lines. I wonder why his was so much longer.
Anyways, a funky issue I was having:
for some reason, if I didn't typedef tNode as *tree, and just passed functions something like
Code
void tAdd(string word, tNode *& root);
it was giving me grief. I saw in the professors examples he did the typedef, and it worked again for some reason. What was I doing wrong exactly? The error I was getting was something along the lines of root not being a member class of tNode*& or something.
This post was edited by Eep on Oct 25 2012 06:30pm