Hello! I just have a quick question about a program I am writing.
So first, here is the code:
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
#include <iostream>
#include <cstring>
using namespace std;
void mostFrequent(char * iptr)
{
char ch;
int i =0;
int max =0;
int secondMax = 0;
int j;
int counter;
while(iptr[i] !='\0')
{
i++;
char * begin;
char * end = iptr +1;
for(begin = iptr; begin != end; begin++)
{
j = 0;
counter = 0;
while(iptr[j])
{
if(*begin == iptr[j])
{
counter++;
}
j++;
}
if(counter > max)
{
max = counter;
ch = *begin;
secondMax =0;
}
else if(counter == max && ch != *begin)
{
secondMax++;
}
}
}
cout << "The max Character is: " << ch << " Which appears: " << max << " amount of times." << endl;
}
int main()
{
const int SIZE = 100;
char strInput[SIZE];
cout << "Please enter a string of text: " << endl;
cin.getline(strInput,SIZE);
mostFrequent(strInput);
return 0;
}
|
What the program is supposed to do is take input from a user, and store it as a string. The string is then accessed using a pointer as an argument for the function mostFrequent, which is then supposed to find the character that pops up the most frequent and print the result.
The problem is that if I type in the sentence "Hello this has a lot of h's." It will print out "The max Character is: h, and it appeared 3 times." So it appears to work.
However, if I type in "The most common character in this is eeeeeeeeee.", it will still say,
"The max Character is: T and it appeared 1 times." So it is apparently only checking the first letter and comparing to see if it appears any more times.
Therefore, I'm wondering why my program is doing this, and not checking through the entire array/string of characters.