C 字符串比较失败?

发布于 2024-11-04 04:08:22 字数 665 浏览 1 评论 0原文

可能的重复:
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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

献世佛 2024-11-11 04:08:22

您正在比较 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) {

一影成城 2024-11-11 04:08:22

在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文