C语言switch语句编译错误排查咨询
Let's walk through the problems in your code and fix them one by one to get your Scrabble scorer working correctly:
1. Core Switch Statement Error
The primary compilation error comes from switch (word):
scrabble.c:50:9: error: statement requires expression of integer type ('string' (aka 'char *') invalid)
switch (word)
^ ~~~~
In C, the switch statement requires an integer-type expression (like char, int, etc.), but you're passing a string (which is a pointer to char). You should be checking individual characters in the word, not the entire string.
2. Invalid Case Labels
Your case isupper(word[i]): syntax is incorrect. Case labels must be compile-time constants, but isupper() returns a runtime value (non-zero if true, 0 if false). This isn't allowed in switch cases—instead, use if/else checks for character casing, or normalize the character to lowercase/uppercase first.
3. Other Syntax & Logic Issues
- Typos:
Pointsshould bePOINTS(your score array is defined as uppercasePOINTS), andBreakneeds to be lowercasebreak(C is case-sensitive). - Incorrect ASCII Values:
'65'and'97'are character literals for the digits '6'/'5' and '9'/'7'—you want the integer values65(ASCII for 'A') or, better yet, use'A'directly for readability. - Early Return: Your
return score;is inside theforloop, so it will exit after the first character. Move it outside the loop to calculate the full word's score. - Non-Alphabetic Characters: You didn't handle non-letters—we need to skip them instead of trying to score them.
Fixed Code
Here's the corrected version of your code with all issues addressed:
#include <ctype.h> #include <cs50.h> #include <stdio.h> #include <string.h> // 字母表中每个字母对应的分值 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) { // 获取两位玩家的输入单词 string word1 = get_string("Player 1: "); string word2 = get_string("Player 2: "); // 计算两个单词的得分 int score1 = compute_score(word1); int score2 = compute_score(word2); // 输出获胜方 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) { int score = 0; int length = strlen(word); for (int i = 0; i < length; i++) { char c = word[i]; // 跳过非字母字符 if (!isalpha(c)) { continue; } // 统一转换为大写字母计算索引 char upper_c = toupper(c); int index = upper_c - 'A'; score += POINTS[index]; } // 循环结束后返回总得分 return score; }
Key Improvements:
- Replaced the invalid
switchwithisalpha()checks and case normalization usingtoupper()—this simplifies the code and avoids switch statement issues. - Added handling for non-alphabetic characters with
continueto skip them. - Fixed typos and corrected the return statement placement.
- Used
'A'instead of hardcoded ASCII values for better readability.
内容的提问来源于stack exchange,提问作者JohnHann-123




