0

I am working on the scrabble lab and I am unsure of where I have gone wrong in my code.

#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};

string uppercase[] = {"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"};
string lowercase[] = {"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 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 (score2 > score1) {
        printf("Player 2 wins\n");
    }
    else if (score1 == score2) {
        printf("Tie\n");
    }
}

int compute_score(string word) {

    int score = 0;

    for (int i = 0; i < strlen(word); i++) {
        if (word[i]) {
            for (int f = 0; f < 26; f++) {
                if (islower(word[i])) {
                    if (strcmp(lowercase[f], &word[i]) == 0) {
                        score += POINTS[i];
                    }
                } else {
                    if (strcmp(uppercase[f], &word[i]) == 0) {
                        score += POINTS[i];
                    }
                }
            }
        }
    }

    return score;
}

It passes 2 of the tests but fails most of them

:) scrabble.c compiles
:) handles letter cases correctly
:( handles punctuation correctly
    expected "Tie!", not "Player 2 wins\..."
:) correctly identifies 'Question?' and 'Question!' as a tie
:( correctly identifies 'hai!' as winner over 'Oh,'
    expected "Player 2 wins!...", not "Tie\n"
:) correctly identifies 'COMPUTER' as winner over 'science'
:( correctly identifies 'Scrabble' as winner over 'wiNNeR'
    expected "Player 1 wins!...", not "Tie\n"
:( correctly identifies 'Skating!' as winner over 'figure?'
    expected "Player 2 wins!...", not "Tie\n"

1 Answer 1

0

Since &word[i] is a char, not a string, I suspect strcmp is giving unpredictable result. Since only one byte is necessary for the compare, perhaps use strncmp instead.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .