C语言 错误:执行“islower”时从“string”强制转换为较小的整数类型“int”

jgovgodb  于 2022-12-22  发布在  其他
关注(0)|答案(1)|浏览(138)
#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("The winner is Player 1!");
    }
    else if (score1 < score2) {
        printf("The winner is Player 2!");
    }
    else {
        printf("Both players have the same score, so it's a draw!");
    }

}

int compute_score(string word)
{
    int sum = 0;
    for (int i = 0; i == strlen(word); i++) {
        if (islower(word)) {
            word = toupper(word);
        }
        string letter = word[i];
        int first_score[i] = POINTS(letter);
        for (int j = 0; j == strlen(first_score); i++) {
            sum = sum + first_score[j];
        }
    }
}

我正在做cs50课程的第二个实验,当我使用islower函数时,这个错误出现了,为什么会这样?假设'word'是一个字符串,那么我必须使用ASCII数字吗?

gajydyqb

gajydyqb1#

  1. islower(int ch), toupper(int ch)需要一个intword是一个指针,因此if (islower(word)) {是个问题。
    相反,代码应取消引用指针
  2. for (int i = 0; i == strlen(word); i++) {是弱的,因为当仅需要检测 * 空字符 * 时,strlen()被调用多次。
    1.当word[i] < 0时,tolower(word[i])是一个问题。最好以unsigned char的形式访问字符串。
  3. POINTS(letter);失败,因为POINTS是一个数组。应注意确保数组从零开始访问并且在范围内。
    1.调用toupper()之前不需要if
// Code could use a type narrower than `int` here.
unsigned char 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) {
  // Access data as if unsigned char
  const unsigned char *uword = (const unsigned char *) string;
  int sum = 0;

  while (*uword) {
    if (isalpha(*uword)) {
      unsigned char ch_index = toupper(*uword) - 'A';
      if (ch_index < sizeof POINTS / sizeof POINTS[0]) {
        sum += POINTS[ch_index];
      }
    }
    uword++'
  }

  return sum;
}

注意:toupper(*uword) - 'A'只适用于ASCII。

相关问题