gpt4 book ai didi

c - 如何正确比较 C 中的字符串?

转载 作者:行者123 更新时间:2023-11-30 16:25:51 26 4
gpt4 key购买 nike

我正在尝试让用户输入一个单词或字符,存储它,然后打印它,直到用户再次键入它,退出程序。我的代码如下所示:

#include <stdio.h>

int main()
{
char input[40];
char check[40];
int i=0;
printf("Hello!\nPlease enter a word or character:\n");
gets(input); /* obsolete function: do not use!! */
printf("I will now repeat this until you type it back to me.\n");

while (check != input)
{
printf("%s\n", input);
gets(check); /* obsolete function: do not use!! */
}

printf("Good bye!");


return 0;
}

问题是我不断打印输入字符串,即使用户的输入(检查)与原始(输入)匹配。我对两者的比较是否错误?

最佳答案

您不能(有效)使用 !=== 比较字符串,您需要使用 strcmp:

while (strcmp(check,input) != 0)

这样做的原因是因为 !=== 只会比较这些字符串的基地址。不是字符串本身的内容。

关于c - 如何正确比较 C 中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53245309/

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