C 字符串比较失败?
我有以下代码;
#include <stdio.h>
#define MAXLINE 2600
char words[4][MAXLINE];
int i;
int main(){
printf("Enter menu option: ");
scanf("%s", words[i]);
printf ("\n %s was entered!", words[i]);
if (words[i]=="help"){
printf("\nHelp was requested");
}
else
{
printf("\nCommand not recognized!");
}
}
if 语句中的数组评估不起作用。我显然做错了什么。有人可以向我解释什么吗?
Possible Duplicate:
C String — Using Equality Operator == for comparing two strings for equality
I have the following code;
#include <stdio.h>
#define MAXLINE 2600
char words[4][MAXLINE];
int i;
int main(){
printf("Enter menu option: ");
scanf("%s", words[i]);
printf ("\n %s was entered!", words[i]);
if (words[i]=="help"){
printf("\nHelp was requested");
}
else
{
printf("\nCommand not recognized!");
}
}
The array evaluation in the if statement isn't working. I am obviously doing something wrong. Can someone explain to me what?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在比较
words[i]
和"help"
指针相等性,而不是字符串相等性。我认为你的意思是:if (strcmp(words[i], "help") == 0) {
You are comparing
words[i]
and"help"
for pointer equality, not string equality. I think you meant:if (strcmp(words[i], "help") == 0) {
在 C 中,字符串(字符序列)被视为字符数组。因此,您不应使用
==
运算符来比较数组。数组大括号
[]
只是语法糖,用于隐藏在幕后进行的指针算术。一般来说,arr[i]
与*(arr + i)
相同。使用此信息,让我们看一下您的比较:words[i]
->*(words + i)
,这是一个指向字符数组的指针。如果要比较字符串,请使用 strncmp。
In C, strings (sequences of characters) are treated as arrays of characters. As a result, you shouldn't compare arrays using the
==
operator.The array braces
[]
are just syntactic sugar to hide the pointer arithmetic that's going on under the hood. In general,arr[i]
is identical to*(arr + i)
. Using this information, let's take a look at your comparison:words[i]
->*(words + i)
, which is a pointer to an array of characters.If you want to compare strings, use strncmp.