我正在尝试让用户输入一个单词或字符,存储它,然后打印它,直到用户再次键入它,退出程序。我的代码如下所示:
#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/48661318/