A
Alf P. Steinbach
I am trying to create a program that will ask for a user to enter
a series of letters (codes) and then print out a table that shows
the codes in decending frequency.
To enter a series a letters, read one line using std::getline.
Only letters will be read into the array.
It's not a good idea to use a raw array here. What you need is to
refer to a count with a letter as key (index). That is most easily
accomplished using a std::map.
A std::map is the most general solution.
For letters, as a special case, a raw array can be an optimization,
but in that case index it using the letter code values.
I have created a struct and array like below.
struct record
{
char inputChar;
int countChar;
};
That is ungood. You don't need it for a raw array, and you don't
need it for a std::map.
const int ARRAY_SIZE = 100;
record list[ARRAY_SIZE];
That is ungood plus. You should reserve all uppercase names for
macros. They're used for constants in Java, but the Java convention
stems from early C where constants had to be expressed as macros.
I have a function that reads the input stream into the array.
void getUserInput(record list[], int &numItems)
{
int count = 0;
char userChar;
cout << "Enter a sequence of characters (end with '.'):";
Why not use end-of-line or end-of-file as the terminator?
cin >> userChar;
Ungood, duplicated code. Choose the right kind of loop so as
to not duplicate code.
while(userChar != '.' && (count < ARRAY_SIZE))
Ungood. Careful with that indention.
{
if(isalpha(userChar)){ //check to see if input is a character
userChar = tolower(userChar); //convert all chars to lower case.
list[count].inputChar = userChar;
count++;
Style, ungood. Use prefix ++, not postfix ++.
}
if(count < ARRAY_SIZE){ //check to see if user has exceeded
Ungood. Careful with that indentation.
cin >> userChar;
}else{
cout << "You have filled the input stream!" <<endl ;
Ungood. Don't explain internals of the program to the user.
}
}
numItems = count ;
}
My question is how should I go about summing the input?
std::map<char> letters;
std::string line;
std::readline( cin, line );
// error checking here, omitted.
for( std::size_t i = 0; i < line.length(); ++i )
{
++letters[line];
}