如何正确比较 C 中的字符串? [英] How do I properly compare strings in C?
问题描述
我正在尝试获取一个程序,让用户输入单词或字符,将其存储,然后打印,直到用户再次键入并退出程序.我的代码如下所示:
I am trying to get a program to let a user enter a word or character, store it, and then print it until the user types it again, exiting the program. My code looks like this:
#include <stdio.h>
int main()
{
char input[40];
char check[40];
int i=0;
printf("Hello!
Please enter a word or character:
");
gets(input); /* obsolete function: do not use!! */
printf("I will now repeat this until you type it back to me.
");
while (check != input)
{
printf("%s
", input);
gets(check); /* obsolete function: do not use!! */
}
printf("Good bye!");
return 0;
}
问题是我一直在打印输入字符串,即使用户输入(检查)与原始输入(输入)匹配.我是否错误地比较了两者?
The problem is that I keep getting the printing of the input string, even when the input by the user (check) matches the original (input). Am I comparing the two incorrectly?
推荐答案
你不能(有用地)使用 !=
或 ==
比较字符串,你需要使用 strcmp
:
You can't (usefully) compare strings using !=
or ==
, you need to use strcmp
:
while (strcmp(check,input) != 0)
这是因为 !=
和 ==
只会比较这些字符串的基地址.不是字符串本身的内容.
The reason for this is because !=
and ==
will only compare the base addresses of those strings. Not the contents of the strings themselves.
这篇关于如何正确比较 C 中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!