compiler error in scrabble calculator

I can't seem to figure out why my code won't compile. The program is supposed to ask a user to input a word and then score it based on the points of each letter. A second set of eyes to point me in the right direction would be very much appreciated. Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  #include <iostream>
#include <string>

using namespace std;
int score(string s);
char scrabbleLetters[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int scrabblePoints[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};

int main()
{
    string sWord;
    cout << "Enter the scrabble word you'd like to score.";
    cin >> sWord;
    cout << "You scored " << score(sWord)<< " points for that word!";

}

int score(string s)
{   int points = 0;
    for (int i = 0; i < s.length(); i++)
    {
        for (int j = 0; j < scrabbleLetters.length(); j++)
        {
            if (s[i] == scrabbleLetters[j])
                points += scrabblePoints[j];
        }
    }
    return points;
}
C++ primitive arrays do not have members like .length(), which is why line 22 doesn't compile. You could make scrabbleLetters a single string that contains all the letters of the alphabet, but allow me to suggest something different: mapping a letter to an array subscript using a little subtraction trick:
1
2
3
4
5
6
7
8
9
10
11
int score(string s)
{
    int points = 0;
    for (int i = 0; i < s.length(); i++)
    {
        //s[i] - 'a' takes advantage of...
        //'a' - 'a' = 0,  'b' - 'a' = 1, 'c' - 'a' = 2, etc.  You can use 0, 1, 2, etc... as array indices
        points += (scrabblePoints[s[i] - 'a']);
    }
    return points;
}

Last edited on
Thanks!
Topic archived. No new replies allowed.