By stuck


2014-12-17 12:26:35 8 Comments

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?

4 comments

@Esakki Thangam 2014-12-17 12:46:44

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!!");

@Karthikeyan.R.S 2014-12-17 12:35:50

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)

@sharon 2014-12-17 12:33:46

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..

@Sourav Ghosh 2014-12-17 12:27:42

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.

Related Questions

Sponsored Content

85 Answered Questions

[SOLVED] How do I make the first letter of a string uppercase in JavaScript?

28 Answered Questions

[SOLVED] How to read a file line-by-line into a list?

61 Answered Questions

[SOLVED] How to replace all occurrences of a string?

31 Answered Questions

58 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

42 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

4 Answered Questions

76 Answered Questions

[SOLVED] How do I iterate over the words of a string?

  • 2008-10-25 08:58:21
  • Ashwin Nanjappa
  • 2151153 View
  • 2923 Score
  • 76 Answer
  • Tags:   c++ string split

18 Answered Questions

[SOLVED] How to pass command line arguments to a rake task

20 Answered Questions

[SOLVED] Best way to parse command line arguments in C#?

Sponsored Content