Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
763 views
in Technique[技术] by (71.8m points)

c - How to properly compare command-line arguments?

I am trying to write a C code which takes arguments in main; thus when I write some strings in cmd, the program doing somethings inside it. But I am doing something wrong and I can't find it.

This is the code:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char * argv[]){   //File name is main.c
    if(argc != 3)
        printf("Wrong!!!!!!!!!");
    else
        if (argv[1] == "-s")
            girls();  //Prints "Girls"
        else if(argv[1] == "-k")
            boys();   //Prints "Boys"
        else
            printf("OMG!!");
}

In the cmd;

gcc -o gender main.c

gender -s pilkington

I enter that commands. Bu the output is always

"OMG!!"

Which part is wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your code, argv[1] == "-s" is the erroneous part. comparison of strings cannot be done with == operator.

To compare strings, you need to use strcmp().

Your code should look like

if ( ! strcmp(argv[1], "-s")) { //code here }

if you want to check if argv[1] contains "-s" or not.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...