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';
}