Reputation: 1
Example:
player 1 enters "all"
player 2 enters "do"
Expected Result: Tie!
Actual Result: Player 2 Wins! (do ends up valuing at 4 points
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
// Points assigned to each letter of the alphabet
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!");
}
else if (score1 == score2)
{
printf("It's a tie!");
}
else
{
printf("Player 2 wins!");
}
}
int compute_score(string word)
{
// TODO: Compute and return score for string
// set initial score to 0
int score = 0;
int letter = 0;
char lower_word[strlen(word)];
// lowercasing the letters in word
for (int j = 0; j < strlen(word); j++)
{
lower_word[j]= tolower(word[j]);
}
// cycle through the string
for (int i = 0, n = strlen(lower_word); i < n; i++)
{
// check to see if character is within scorable range
if (lower_word[i] >= 'a' && lower_word[i] <= 'z')
{
// make the value be within the list of points
letter = lower_word[i] - 97;
// grab score and add it to current score
score = score + POINTS[letter];
}
// if score isn't a value within the range
else
{
// add nothing to the current score
score = score + 0;
}
}
// returns final score value
return score;
}
Upvotes: 0
Views: 48
Reputation: 11
It seems the following piece in compute_score leads to error:
char lower_word[strlen(word)];
Assuming strlen(word) is 5, then lower_word has 5 char space (5 bytes). BUT, in C, a char string needs 1 more byte to contain the ending '\0'; so actually lower_word needs 6 bytes to contain a char string.
In your code, lower_word has no (guarantted) ending '\0', so the strlen(lower_word) in the follong loop may work for unknown times...
for (int i = 0, n = strlen(lower_word); i < n; i++)
What modification I suggest is:
char lower_word[strlen(word) + 1] = {0};
Upvotes: 1