repeated letters

ok so i have a program which is supposed to generate a random char array, then count the array, then display the count for each letter. the function display count just reuses the function count letters. anyways, the issue i'm having is that when it counts how many times the letter appears in the array, it only counts the first letter of the array, and counts it multiple times, even though the when it displays the array, it may only show that letter once.

here is the source code:
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;

int num;
char *cp;
char *createArray(int);
char getLowerCaseLetter();
int *countLetters(int num);
int displayLetters(char *, int);
int displayCount(char *, int);

int main()
{
srand(time(0));
cout << "Enter an integer to set the array size: ";
cin >> num;
char * ap;
ap = createArray(num);
displayLetters(ap, num);
displayCount( cp, num);
}

char getLowerCaseLetter()
{
return (char) ('a'+ rand()%25);
}

char *createArray(int num)
{
char character[num];
cp = new char[num];
for (int ix = 0; ix < num; ix++)
{
getLowerCaseLetter();
*(cp + ix) = getLowerCaseLetter();
}
return cp;
}

int *countLetters(int num)
{
for(int j = 0; j < num; j++)
{
char letter = *cp;
int count = 0;
for (int k = 0; k < num; k++)
{
if (letter = *cp)
count++;
}
cout << "The letter " << letter << " appeared " << count << " times.\n";
}
}

int displayLetters(char * , int num)
{
for (int m = 0; m < num; m++)
{
cout << *(cp+m) << " ";
}
cout << endl;
}

int displayCount(char *, int num)
{
int *mp;
mp = countLetters(num);
}
the tricky part is finding the counts of each letter. you can use a struct because the members are public by default. Here you keep the char and the number of times it appears. You would fill the struct with the char at the same time you fill the array. (you could do both, but i think the idea is to call functions.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
struct LetterCount
{
    LetterCount():Letter(0), Count(0){};
    char Letter;
    unsigned int Count;
};

//....
//create the array of letters
LetterCount* LC;
LC = new LetterCount[num];

//...
//find duplicates

for(int i = 0; i < num; i++)
{
     for(int j = 0; j < num; j++)
     {
        if(*cp[i] == *LC[j].Letter)
        {
           *LC[j].Count++;
        }
      }
}

//...


then you just output the info from the LetterCount struct.

Last edited on
You might be a genius. Or you just know what you're doing. (Unlike me. But if I did, then I probably wouldn't be posting in the beginner's section. Gotta start somewhere. Even John McCarthy didn't know what he was doing once upon a time.)
Last edited on
Topic archived. No new replies allowed.