How to compare command line arguments?

I am trying to write C code that takes arguments in main; that way, when I write some lines in cmd, the program does something inside. But I am doing something wrong, and I cannot 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 cmd;

gcc -o gender main.c

gender -s pilkington

I enter these commands. Bu exit always

"OMG !!"

Which part is wrong?

+5
source share
4 answers

In your code, argv[1] == "-s" is the erroneous part. string comparisons cannot be performed using the == 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.

+9
source

if you check argv[1] == "-s" , the condition will be invalid. since this 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 it.

+1
source

Compare the two lines 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!!"); 
+1
source

You need to compare the string using strcmp function. You cannot just check a string in an equality operator.

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

Try this in your code.

 if ((strcmp(argv[1],"-s")==0) 
0
source

Source: https://habr.com/ru/post/1209348/


All Articles