gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:14:13 24 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/53607062/

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