gpt4 book ai didi

在循环中比较C中的两个字符串

转载 作者:太空宇宙 更新时间:2023-11-04 01:48:58 25 4
gpt4 key购买 nike

我正在编写代码来查看用户的输入是否等同于已经声明的字符串。程序使用 strcmp 函数循环直到输入与字符串相同,但由于某种原因程序不比较字符串,因此循环出现故障。代码如下:

int main()
{
char passcode[3]="ZZZ";
char input[3];
int check;
while(check!=0)
{
printf("What is the password?\n");
gets(input);
check=strcmp(passcode, input);
}
printf("You crack the pass code!");
return 0;
}

最佳答案

主要问题在这里:

char passcode[3]="ZZZ";
char input[3];

C 中的字符串由一个字符序列和一个空字节组成。 passcode 不够大,无法容纳用于初始化的字符串的空字节。因此,当您尝试通过将其传递给 strcmp 来将其用作字符串时,它会读取数组的末尾。这样做会调用 undefined behavior .

同样,input 也不够大,无法容纳足够大的字符串进行比较。

您也没有初始化 check,因此您第一次进入循环时它的值是未知的。

另一个问题是gets的使用。这个函数很危险,因为它不检查用户输入的字符串是否适合给定的缓冲区。如果太大,这将再次调用未定义的行为。

使您的数组更大以容纳用户输入和目标字符串,并使用 fgets 而不是 gets。您还应该将 while 循环更改为 do..while,因为您需要至少进入循环一次。

#include <stdio.h>

int main()
{
char passcode[]="ZZZ"; // array is automatically sized
char input[50];
int check;

do {
printf("What is the password?\n");
fgets(input, sizeof(input), stdin);
check=strcmp(passcode, input);
} while (check!=0);
printf("You crack the pass code!");
return 0;
}

关于在循环中比较C中的两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47722411/

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