gpt4 book ai didi

不能运行的C语言程序?

转载 作者:太空宇宙 更新时间:2023-11-04 05:14:39 24 4
gpt4 key购买 nike

用户输入一个 secret 词,然后从字母表中选择一个字母,如果该字母在 secret 词中,它就会变成一个星号。我认为问题出在两个 for 循环中,因为它似乎没有用星号替换字母。

int main ()
{
char secretword[20] = {};
char alphabet[27] = {"abcdefghijklmnopqrstuvwxyz"};
char guess;
int i = 0, k = 0;
int length = 0;

length = strlen(secretword);

printf("You Get six chances to guess all of the letters in a phrase\n");
printf("Enter the secret word/phrase: ");
scanf("%s", &secretword);
printf("Past guesses: ");
printf("%s\n", alphabet);
printf("Guess a character: ");
scanf("%s", &guess);

for(i = 0; i < 27; i++)
{
for(k = 0; k < length; k++)
{
if(secretword[k] == alphabet[i])
{
secretword[k] = '*';
}
}
}

printf("%s", secretword);

return 0;
}

最佳答案

首先,有一个很大的逻辑错误。两个 for 循环:

  for(i = 0; i < 27; i++)
{
for(k = 0; k < length; k++)
{
if(secretword[k] == alphabet[i])
{
secretword[k] = '*';
}
}
}

说:

  • 对于字母表中的所有字符,
    • 遍历字符串中的所有字符,然后
      • 如果字符串中的那个字符等于当前字母字符:
        • 用星号代替。

因为您要遍历整个字母表,所以您会将所有字符串替换为“*”。你可能想要的是这样的:

for(k = 0; k < length; k++)
{
if(secretword[k] == guess)
{
secretword[k] = '*';
}
}

相反。

还有一些问题。这需要读入密码之后:

 length = strlen(secretword);

否则你会读到未初始化单词的长度。把它改成这样:

 printf("You Get six chances to guess all of the letters in a phrase\n");
printf("Enter the secret word/phrase: ");
scanf("%s", &secretword);
length = strlen(secretword);

另外,这个:

 scanf("%s", &guess);

应该是:

 scanf("%c", &guess);

因为您打算只读取 char 而不是字符串。


此外,这一行中的 27:

char alphabet[27] = {"abcdefghijklmnopqrstuvwxyz"};

是正确的,因为您想在字符串末尾包含空终止符。

但是,这:

for(i = 0; i < 27; i++)

将读取到 alphabet[26],这将是一个 '\0'。您可能不想替换字符串中的这些 '\0'(如果您只是转到 strlen(secretword),您将看不到任何内容) > 个字符 - 因为 strlen() 计数到第一个 '\0')。将循环更改为仅转到 26 个字符可以阻止您对 secretword 进行不必要的传递。应该是

for(i = 0; i < strlen(alphabet); i++)

或者,甚至更好(如 wildplasser 所建议):

char alphabet[] = {"abcdefghijklmnopqrstuvwxyz"}; 

....

for(i = 0; i < sizeof alphabet -1; i++)

最后一件事 - 如果您在 secretword 数组中没有足够的空间来保存读入的字符串,您的程序将会崩溃。您可以通过让 scanf 只读取 19 个字符来解决这个问题:

scanf("%19s", &secretword);

请注意,scanf 将以 '\0' 终止字符串,因此 %19s 最多可将 20 个字节放入字符串中。

关于不能运行的C语言程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9712308/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com