繁体   English   中英

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

[英]Comparing two strings in C in a loop

我正在编写一个代码来查看用户的输入是否等同于已经声明的字符串。 程序循环直到输入与字符串相同,使用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它会读取数组的末尾。 这样做会调用未定义的行为

同样, input不足以容纳足够大的字符串来进行比较。

你也没有初始化check ,所以第一次进入循环时它的值是未知的。

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

使您的数组更大以保存用户的输入以及目标字符串,并使用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;
}

上面建议的代码无法识别输入。 它可能不会工作,并将陷入while循环。 我建议使用scanf作为输入更容易,然后像对strcmp一样比较字符串。 如果输入正确,则让进入并退出while循环。 尝试这个:

#include <stdio.h>
int main()
{
  char input[3];
  printf ("\nHit the pass code!\npass code: ");
  while (input != "ZZZ") {
    scanf ("%s",&input);
    if (strcmp(input, "ZZZ") == 0){
      printf ("\nYou crack the pass code!!\n\n");
      break;
    } else {
      printf ("Wroooong!\n pass code: ");
    }
  } 
  return 0;
}

我知道发生了什么。 您的输入字符串只有三个三字节,您正在使用unsafe gets进行读取。 获取将ZZZ的输入按预期放入输入变量,但它将终止空值放在密码的第一个字节中。

将输入缓冲区的大小更改为999,事情会更好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM