C 参数不起作用?

发布于 2024-08-21 21:41:03 字数 459 浏览 4 评论 0原文

为什么这不起作用? 当我尝试使用 -l 或 -s 作为第一个参数时,if 语句不适用。他们总是转到 else 语句。

#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
    if (argv[1] == "-l")
    {
        printf("Yay!\n");
    }
    else if (argv[1] == "-s")
    {
        printf("Nay!\n");
    }
    else
    {
        printf("%s\n", argv[1]);
    }
        return 0;
}

Why doesn't this work?
When I try to use -l or -s as the first argument, the if statements don't take. They always go to the else statement.

#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
    if (argv[1] == "-l")
    {
        printf("Yay!\n");
    }
    else if (argv[1] == "-s")
    {
        printf("Nay!\n");
    }
    else
    {
        printf("%s\n", argv[1]);
    }
        return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

花开半夏魅人心 2024-08-28 21:41:03

您不能使用 == 运算符来比较字符串 - 请使用 strcmp() 代替。

通过使用 == 比较字符串,您可以比较 char * 指针的地址,而不是字符串值。

You cannot compare strings using == operator - use strcmp() instead.

By comparing strings using == you are comparing the addresses of char * pointers, not string values.

无人问我粥可暖 2024-08-28 21:41:03

在 C 中,字符串是通过 strcmp 函数进行比较的。相反,您只比较指针。所以:

if (strcmp(argv[1],"-l") == 0)
{
    printf("Yay!\n");
}

In C strings are compares by strcmp function. Instead your compares just pointers. So:

if (strcmp(argv[1],"-l") == 0)
{
    printf("Yay!\n");
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文