A couple of different errors here.
First, this code to output the results:
36 37 38 39 40 41 42
|
for (int i=0; i < 26; i++)
{
if (count[i])
{
cout << char(i + 'a') << ": " << count[i] << '\n';
}
}
|
The above is enclosed within the loop which reads a word from the file, thus it is executed many times, rather than just once. That block of code should be moved outside the while loop which starts at line 27.
The second error is the use of
.eof()
When this is used, it is almost always an error, and should be avoided. The problem is, the file input command is at line 29,
zelda >> message;
Regardless of whether this input fails or succeeds, the remainder of the code in the loop is processed. Only after that is the eof() checked, which is too late.
In this program, if the last word in the file is followed by any whitespace, the last word will be counted twice.
This is the correct way to do it:
1 2 3 4 5 6 7 8
|
string message;
while (zelda >> message)
{
const char *buffer = message.c_str();
while(add_letter(*buffer++, count));
}
|
However, that is more complicated than necessary. It can be simplified to this:
1 2 3 4 5 6
|
char letter;
while (zelda >> letter)
{
add_letter(letter, count);
}
|