How to properly compare command-line arguments?
Asked Answered
H

4

9

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?

Headpin answered 17/12, 2014 at 12:26 Comment(1)
== will compare the adresses of the pointers, not the content of the String.Cass
P
13

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.

Powered answered 17/12, 2014 at 12:27 Comment(0)
L
2

Compare the two strings using the strcmp(s1,s2) function.

            if (strcmp(argv[1],"-s")==0)
                    girls();  //Prints "Girls"
            else if(strcmp(argv[1],"-k")==0)
                    boys();   //Prints "Boys"
            else
                    printf("OMG!!");
Londrina answered 17/12, 2014 at 12:46 Comment(0)
M
1

if you check the argv[1] == "-s" the condition will not be true. since it is a string you can use the strcmp function.

     if(( strcmp(argv[1],"-s")) == 0)
     girls();
     else if ((strcmp(argv[1],"-k")) == 0)
     boys();

Try this..

Moquette answered 17/12, 2014 at 12:33 Comment(0)
R
0

You have to compare the string using the strcmp function. You cannot simply check the string in equality operator.

  int strcmp(const char *s1, const char *s2);

Try this in your code.

if ((strcmp(argv[1],"-s")==0)
Rutkowski answered 17/12, 2014 at 12:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.