| re: Counting and summing elements in an array? Help!
On Wed, 4 Feb 2004 20:27:59 -0600, "SunMan" <css_67@yahoo.com> wrote:
[color=blue]
>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.[/color]
To enter a series a letters, read one line using std::getline.
[color=blue]
>Only letters will be read into the array.[/color]
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.
[color=blue]
>I have created a struct and array like below.
>
>struct record
>{
>
>char inputChar;
>int countChar;
>};[/color]
That is ungood. You don't need it for a raw array, and you don't
need it for a std::map.
[color=blue]
>const int ARRAY_SIZE = 100;
>record list[ARRAY_SIZE];[/color]
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.
[color=blue]
>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 '.'):";[/color]
Why not use end-of-line or end-of-file as the terminator?
[color=blue]
>cin >> userChar;[/color]
Ungood, duplicated code. Choose the right kind of loop so as
to not duplicate code.
[color=blue]
>
> while(userChar != '.' && (count < ARRAY_SIZE))[/color]
Ungood. Careful with that indention.
[color=blue]
> {
> 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++;[/color]
Style, ungood. Use prefix ++, not postfix ++.
[color=blue]
> }
> if(count < ARRAY_SIZE){ //check to see if user has exceeded[/color]
Ungood. Careful with that indentation.
[color=blue]
> cin >> userChar;[/color]
[color=blue]
> }else{
> cout << "You have filled the input stream!" <<endl ;[/color]
Ungood. Don't explain internals of the program to the user.
[color=blue]
> }
> }
> numItems = count ;
> }
>
>
>My question is how should I go about summing the input?[/color]
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[i]];
} |