开发者

C Arguments Not Working?

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;
}


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

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


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜