我正在尝试让一个程序让用户输入一个单词或字符,存储它,然后打印它,直到用户再次键入它,退出程序。我的代码如下所示:
#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;
}
问题是我一直在打印输入字符串,即使用户的输入(check)与原始的( input )匹配。我是不是错误地比较了这两个?
发布于 2011-11-04 10:24:17
不能(有效地)使用!=
或==
比较字符串,需要使用strcmp
while (strcmp(check,input) != 0)
这是因为!=
和==
只会比较这些字符串的基地址。而不是字符串本身的内容。
发布于 2011-11-04 10:29:52
好的,有几件事:gets
is unsafe和应该被替换为fgets(input, sizeof(input), stdin)
,这样你就不会得到缓冲区溢出。
接下来,要比较字符串,必须使用strcmp
,其中返回值0表示两个字符串匹配。使用相等运算符(即!=
)比较两个字符串的地址,而不是它们内部的单个char
。
还要注意,虽然在本例中不会造成问题,但fgets
也将换行符'\n'
存储在缓冲区中;gets()
则不会。如果将来自fgets()
的用户输入与字符串文字(如"abc"
)进行比较,它将永远不会匹配(除非缓冲区太小,以至于'\n'
无法放入其中)。
https://stackoverflow.com/questions/8004237
复制相似问题