0

为什么这不起作用?

我认为这个 if 语句中的逻辑是有缺陷的,但我确定到底出了什么问题。

编辑:我忘了添加头文件以及 int main(void)。现在一切都应该在那里

int main(void){
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
string word = "APPPLE";
string alphabet[] = {"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"};


    if (word[0] == alphabet[0])
    {
        printf("this program works");
    }
}

                  
4

2 回答 2

0

C 中没有称为“字符串”的内置名称。相反,字符数组用于处理字符串。以下代码可能会对您有所帮助。

#include <stdio.h>

int main() {

     char word[] = "APPPLE";

     char alphabet[] = {'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'};

     if (word[0] == alphabet[0]) 

        printf("this program works");

    return 0;
}
于 2022-03-03T17:30:12.713 回答
0

指针字(字符串是 char * 类型的 typedef)指向字符串字面量的第一个字符"APPLE"

string word = "APPPLE";

所以表达式word[0]有 type char

数组的元素alphabet指向另一个字符串文字。

string alphabet[] = {"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.char *

在 if 语句中,您试图将字符words[0]与指针进行比较alphabet[0]

if (word[0] == alphabet[0])
{
    printf("this program works");
}

这没有任何意义。

您需要的是以下内容

if (word[0] == alphabet[0][0])
{
    printf("this program works");
}

虽然最好像这样声明数组字母

string alphabet = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ"};

在这种情况下,if 语句看起来像

if (word[0] == alphabet[0])
{
    printf("this program works");
}
于 2022-03-03T17:45:01.913 回答