0

I would like to write a program that performs different function based on the argument provided.

For example:

$ ./program -a //line 1
$ ./program -b //line 2

if I enter line 1 in terminal, I want it to print "Hi" if I enter line 2 in terminal, I want it to print "Bye"

Here is my current logic, which does not work in C:

int main (int argc, char *argv[])
{
    if (argv[1] == "-a"){
        printf("Hi");
    } else if (argv[1] == "-b")
    {
        printf("Bye");
    }

Can anyone help me fix my code in order to achieve my objective?

Thanks in advance!

sticky bit
  • 36,626
  • 12
  • 31
  • 42
A.Nassar
  • 27
  • 5
  • 3
    You can't compare a string with `==`, strings are character arrays. You can use something like `strcmp`. – Thomas Jager Aug 28 '20 at 17:50
  • 1
    Alternatively, if you know your CL arguments will always be in the format {-x|x of alphabet} you can write: if(argv[1][0] == '-') { if(argv[1][1] == 'p')...} However, this could get problematic as you add more arguments or allow multicharacter args, so the elegant solution would be the one Thomas suggested above. – kiwibg Aug 28 '20 at 17:54

1 Answers1

1

You should use strcmp() to compare strings in C.

#include <stdio.h>
#include <string.h> /* for strcmp() */

int main (int argc, char *argv[])
{
    if (strcmp(argv[1], "-a") == 0){
        printf("Hi");
    } else if (strcmp(argv[1], "-b") == 0)
    {
        printf("Bye");
    }
    return 0;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • Thanks !!! it works. will accept it as an answer when stack overflow allows It :D – A.Nassar Aug 28 '20 at 17:56
  • Hmm, in this particular case where the strings come from the arguments or literals, it might make no difference. But in general `strncmp()`, if available, might be the safer choice for comparing strings? – sticky bit Aug 28 '20 at 19:34