Reputation: 1
when I type ./scrabble and enter Player 1 and 2's words, the result is segmentation fault(core dumped). I looked at other similar solutions and they had no errors, so where did i make the mistake.
int POINTS[] = {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 compute_score(string word);
int main(void)
{
// Get input words from both players
string word1 = get_string("Player 1: ");
string word2 = get_string("Player 2: ");
// Score both words
int score1 = compute_score(word1);
int score2 = compute_score(word2);
// TODO: Print the winner
if ( score1 > score2 )
{
printf("Player 1 Wins\n");
}
else if (score1 < score2)
{
printf("player 2 Wins\n");
}
else if (score1 == score2)
{
printf("Tie\n");
}
}
int compute_score(string word)
{
// TODO: Compute and return score for string
int score= 0;
for (int i = 0; i < strlen(word); i++)
{
if islower(word)
{
score = POINTS[(word[i])-65];
}
if isupper(word)
{
score = POINTS[(word[i])-97];
}
}
return score;
}
Upvotes: 0
Views: 200
Reputation: 781984
You're subtracting the wrong values from the character codes, because 65
is the ASCII code for A
, not a
. Avoid problems like this by using character literals rather than ASCII codes.
The argument to islower()
and isupper()
must be the current character in the word word[i]
, not the whole string word
.
You're also not adding to the score, you're overwriting it in the loop. So the score will just be for the last letter in the word. Use +=
to add to the variable instead of =
to assign it.
int compute_score(string word)
{
int score= 0;
for (int i = 0; i < strlen(word); i++)
{
if islower(word[i])
{
score += POINTS[(word[i])-'a'];
}
else if isupper(word[i])
{
score += POINTS[(word[i])-'A'];
}
}
return score;
}
Upvotes: 2