problem understanding a panagram code


#include <iostream>
#include <vector>
#include <cctype>
using namespace std;

const int ALPHA_SIZE = 26;

int main()
{
string line;

while (getline(cin, line))
{
vector<int> letter_count(ALPHA_SIZE);
// int letter_count[ALPHA_SIZE] = { 0 }; // alternativ

// Räkna förekomsten av varje bokstav på raden.
for (unsigned int i = 0; i < line.length(); ++i)
{
char c = line[i];

if (isalpha(c))
{
++letter_count[toupper(c) - 'A']; <------- dont understand this this function and why -A?
}
}

// Kontrollera om raden uppfyller kraven för panagram.
bool is_anagram = true;
bool is_perfect = true;
int n_letters = 0;

for (int i = 0; i < ALPHA_SIZE; ++i)
{
n_letters += letter_count[i];

if (letter_count[i] > 1)
{
is_perfect = false;
}

if (letter_count[i] == 0)
{
is_anagram = false;
break; // out of for loop
}
}

if (is_anagram)
{
cout << n_letters << ": " << line;
if (is_perfect) cout << " [PERFEKT]";
cout << '\n';
}

}

return 0;
}
Last edited on
The letters A-Z are next to each other in any character set. See the ASCII table, for instance:
http://www.asciitable.com/

So by subtracting 'A', you get the alphabet index for an uppercase character, i.e. 0 for A, 1 for B and 25 for Z.
This is then used as an array index to increase the count for that particular letter.
Thank you very much for the information!
Topic archived. No new replies allowed.