I'm trying to do a simple scrabble game in the cs50 pset Week 2 and the function, int compute_score(string word)
, can't handle an input that uses punctuation, even though it's roughly the same as the correct answer using less lines of code by converting all input to uppercase. Here's the code below, but all you really need to look at is the function that I named above:
#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()
{
// 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
{
printf("Tie!\n");
}
}
int compute_score(string word)
{
// TODO: Compute and return score for string
//Initialize score
int score = 0;
//Convert array of chars to uppercase and solve
for (int i = 0, N = strlen(word); i < N; i++)
{
score = score + POINTS[toupper(word[i]) - 65];
}
return score;
}
Before I got to this point, I was having trouble using toupper
on individual chars until I watched a video explaining the logic of using an ASCII chart and how to iterate chars in a string from the lecture. So inside the for loop, I wrote:
//Convert array of chars to uppercase and solve
for (int i = 0, N = strlen(word); i < N; i++)
{
score = score + POINTS[toupper(word[i]) - 65];
}
return score;
I made the decision to convert the input to all uppercase because since characters like, A
and g
have the same value as their capitalized/non-capitalized counterpart, I thought it would just be simpler to convert it to uppercase so that the logic is simpler, faster, and more efficiently written. Made more sense in my head, too. However, when I use the check50 thing, everything gets put in the green EXCEPT for anything that has punctuation (with one exception at the end). Here's what the terminal test shows:
Now I just don't understand this at all, because in my eyes, it's almost totally the same as the correct answer, which is this:
for (int i = 0, N = strlen(word); i < N; i++)
{
if (isupper(word[i]))
{
score += POINTS[word[i] - 'A'];
}
else if (islower(word[i]))
{
score += POINTS[word[i] - 'a'];
}
}
I have no idea why it's not working. I'm thinking that for some reason, it's grading the punctuation. That doesn't make sense though, because since toupper
is designed to only work with alphabetical characters, it should be excluding special characters, rendering their value to zero. Does anyone have any suggestions for what's going wrong?