-4

I'm trying to find the amount of letters of the alphabet from a file I have. I can get the first letter A to give me the correct number, but when the for loop goes through it only gives me 0 for the rest of the letters. I feel like it has to do with my .get() not starting at the beginning of the file again. What do I need to do to fix this? Thanks!

ifstream openFile("data.txt");
int numberOfLetters(0);
char letter;
for (int i = 0; i < 26; i++)
{
    numberOfLetters = 0;
    openFile.clear();
    while (!openFile.eof())
    {

        openFile.get(letter);
        if (letter == char(i + 97) || letter == char(i + 65))
        {
            numberOfLetters++;
        }
    }
    cout << numberOfLetters;
}

1 Answers1

0

The problem is your outer loop: It looks like you want to use this loop to check if the characters taken from the file are equal to certain characters from a certain range. If this is the case, performing the input within the loop is not the way to go.

On the first iteration of the loop, the file will be read completely such that by the second iteration openFile.get(letter) won't extract anything into letter, leaving it with its previous value, same for the rest of the outer iterations. It must be that the last value previous had didn't pass the if() statement test, so numberOfLetter didn't increment.

The solution is to change the way you check if the character is alphabetic. Characters are represented using the ASCII format, which are just integers mapped to characters. Since characters are really integers, you can use arithmetic operations on them. Moreover, characters are represented alphabetically in ASCII, so you can simply compare their values to see if they are in the range of alphabetic characters:

while (openFile.get(letter))
{
    if (('a' <= letter && letter <= 'z') || ('A' <= letter && letter <= 'Z'))
    {
        numberOfLetters++;
    }
}
cout << numberOfLetters;

Fortunately the standard library provides a function std::isalpha() that does this for you.

...
if (std::isalpha(letter))
{
    numberOfLeters++;
}
...

Based on your comment, checking if a character is alphabetic is not enough. Instead, use a data structure like std::map in order to keep a total count of the number of certain characters:

#include <map>

std:map<char, std::size_t> alpha_count;

while (openFile.get(letter))
{
    if (std::isalpha(letter))
        alpha_count[letter]++;
}

Now to print how many specific characters there are, loop through the map and print the character's count():

for (auto&& c : alpha_count)
{
    std::cout << "# of " << c << ": " << alpha_count.count(c) << '\n';
}
David G
  • 94,763
  • 41
  • 167
  • 253